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.

906 lines
28KB

  1. <?php
  2. use Friendica\App;
  3. use Friendica\Core\System;
  4. use Friendica\Core\Config;
  5. use Friendica\Util\Lock;
  6. if (!file_exists("boot.php") && (sizeof($_SERVER["argv"]) != 0)) {
  7. $directory = dirname($_SERVER["argv"][0]);
  8. if (substr($directory, 0, 1) != "/") {
  9. $directory = $_SERVER["PWD"]."/".$directory;
  10. }
  11. $directory = realpath($directory."/..");
  12. chdir($directory);
  13. }
  14. require_once("boot.php");
  15. function poller_run($argv, $argc){
  16. global $a, $poller_up_start, $poller_db_duration;
  17. $poller_up_start = microtime(true);
  18. if (empty($a)) {
  19. $a = new App(dirname(__DIR__));
  20. }
  21. require_once ".htconfig.php";
  22. require_once "include/dba.php";
  23. dba::connect($db_host, $db_user, $db_pass, $db_data);
  24. unset($db_host, $db_user, $db_pass, $db_data);
  25. Config::load();
  26. // Check the database structure and possibly fixes it
  27. check_db(true);
  28. // Quit when in maintenance
  29. if (Config::get('system', 'maintenance', true)) {
  30. return;
  31. }
  32. $a->set_baseurl(Config::get('system', 'url'));
  33. load_hooks();
  34. // At first check the maximum load. We shouldn't continue with a high load
  35. if ($a->maxload_reached()) {
  36. logger('Pre check: maximum load reached, quitting.', LOGGER_DEBUG);
  37. return;
  38. }
  39. // We now start the process. This is done after the load check since this could increase the load.
  40. $a->start_process();
  41. // Kill stale processes every 5 minutes
  42. $last_cleanup = Config::get('system', 'poller_last_cleaned', 0);
  43. if (time() > ($last_cleanup + 300)) {
  44. Config::set('system', 'poller_last_cleaned', time());
  45. poller_kill_stale_workers();
  46. }
  47. // Count active workers and compare them with a maximum value that depends on the load
  48. if (poller_too_much_workers()) {
  49. logger('Pre check: Active worker limit reached, quitting.', LOGGER_DEBUG);
  50. return;
  51. }
  52. // Do we have too few memory?
  53. if ($a->min_memory_reached()) {
  54. logger('Pre check: Memory limit reached, quitting.', LOGGER_DEBUG);
  55. return;
  56. }
  57. // Possibly there are too much database connections
  58. if (poller_max_connections_reached()) {
  59. logger('Pre check: maximum connections reached, quitting.', LOGGER_DEBUG);
  60. return;
  61. }
  62. // Possibly there are too much database processes that block the system
  63. if ($a->max_processes_reached()) {
  64. logger('Pre check: maximum processes reached, quitting.', LOGGER_DEBUG);
  65. return;
  66. }
  67. // Now we start additional cron processes if we should do so
  68. if (($argc <= 1) || ($argv[1] != "no_cron")) {
  69. poller_run_cron();
  70. }
  71. $starttime = time();
  72. // We fetch the next queue entry that is about to be executed
  73. while ($r = poller_worker_process($passing_slow)) {
  74. // When we are processing jobs with a lower priority, we don't refetch new jobs
  75. // Otherwise fast jobs could wait behind slow ones and could be blocked.
  76. $refetched = $passing_slow;
  77. foreach ($r AS $entry) {
  78. // Assure that the priority is an integer value
  79. $entry['priority'] = (int)$entry['priority'];
  80. // The work will be done
  81. if (!poller_execute($entry)) {
  82. logger('Process execution failed, quitting.', LOGGER_DEBUG);
  83. return;
  84. }
  85. // If possible we will fetch new jobs for this worker
  86. if (!$refetched && Lock::set('poller_worker_process', 0)) {
  87. $stamp = (float)microtime(true);
  88. $refetched = find_worker_processes($passing_slow);
  89. $poller_db_duration += (microtime(true) - $stamp);
  90. Lock::remove('poller_worker_process');
  91. }
  92. }
  93. // To avoid the quitting of multiple pollers only one poller at a time will execute the check
  94. if (Lock::set('poller_worker', 0)) {
  95. $stamp = (float)microtime(true);
  96. // Count active workers and compare them with a maximum value that depends on the load
  97. if (poller_too_much_workers()) {
  98. logger('Active worker limit reached, quitting.', LOGGER_DEBUG);
  99. return;
  100. }
  101. // Check free memory
  102. if ($a->min_memory_reached()) {
  103. logger('Memory limit reached, quitting.', LOGGER_DEBUG);
  104. return;
  105. }
  106. Lock::remove('poller_worker');
  107. $poller_db_duration += (microtime(true) - $stamp);
  108. }
  109. // Quit the poller once every 5 minutes
  110. if (time() > ($starttime + 300)) {
  111. logger('Process lifetime reached, quitting.', LOGGER_DEBUG);
  112. return;
  113. }
  114. }
  115. logger("Couldn't select a workerqueue entry, quitting.", LOGGER_DEBUG);
  116. }
  117. /**
  118. * @brief Returns the number of non executed entries in the worker queue
  119. *
  120. * @return integer Number of non executed entries in the worker queue
  121. */
  122. function poller_total_entries() {
  123. $s = q("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` <= '%s' AND NOT `done`", dbesc(NULL_DATE));
  124. if (dbm::is_result($s)) {
  125. return $s[0]["total"];
  126. } else {
  127. return 0;
  128. }
  129. }
  130. /**
  131. * @brief Returns the highest priority in the worker queue that isn't executed
  132. *
  133. * @return integer Number of active poller processes
  134. */
  135. function poller_highest_priority() {
  136. $s = q("SELECT `priority` FROM `workerqueue` WHERE `executed` <= '%s' AND NOT `done` ORDER BY `priority` LIMIT 1", dbesc(NULL_DATE));
  137. if (dbm::is_result($s)) {
  138. return $s[0]["priority"];
  139. } else {
  140. return 0;
  141. }
  142. }
  143. /**
  144. * @brief Returns if a process with the given priority is running
  145. *
  146. * @param integer $priority The priority that should be checked
  147. *
  148. * @return integer Is there a process running with that priority?
  149. */
  150. function poller_process_with_priority_active($priority) {
  151. $s = q("SELECT `id` FROM `workerqueue` WHERE `priority` <= %d AND `executed` > '%s' AND NOT `done` LIMIT 1",
  152. intval($priority), dbesc(NULL_DATE));
  153. return dbm::is_result($s);
  154. }
  155. /**
  156. * @brief Execute a worker entry
  157. *
  158. * @param array $queue Workerqueue entry
  159. *
  160. * @return boolean "true" if further processing should be stopped
  161. */
  162. function poller_execute($queue) {
  163. global $poller_db_duration, $poller_last_update;
  164. $a = get_app();
  165. $mypid = getmypid();
  166. // Quit when in maintenance
  167. if (Config::get('system', 'maintenance', true)) {
  168. logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
  169. return false;
  170. }
  171. // Constantly check the number of parallel database processes
  172. if ($a->max_processes_reached()) {
  173. logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
  174. return false;
  175. }
  176. // Constantly check the number of available database connections to let the frontend be accessible at any time
  177. if (poller_max_connections_reached()) {
  178. logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
  179. return false;
  180. }
  181. $argv = json_decode($queue["parameter"]);
  182. // Check for existance and validity of the include file
  183. $include = $argv[0];
  184. if (!validate_include($include)) {
  185. logger("Include file ".$argv[0]." is not valid!");
  186. dba::delete('workerqueue', array('id' => $queue["id"]));
  187. return true;
  188. }
  189. require_once($include);
  190. $funcname = str_replace(".php", "", basename($argv[0]))."_run";
  191. if (function_exists($funcname)) {
  192. // We constantly update the "executed" date every minute to avoid being killed too soon
  193. if (!isset($poller_last_update)) {
  194. $poller_last_update = strtotime($queue["executed"]);
  195. }
  196. $age = (time() - $poller_last_update) / 60;
  197. $poller_last_update = time();
  198. if ($age > 1) {
  199. $stamp = (float)microtime(true);
  200. dba::update('workerqueue', array('executed' => datetime_convert()), array('pid' => $mypid, 'done' => false));
  201. $poller_db_duration += (microtime(true) - $stamp);
  202. }
  203. poller_exec_function($queue, $funcname, $argv);
  204. $stamp = (float)microtime(true);
  205. if (dba::update('workerqueue', array('done' => true), array('id' => $queue["id"]))) {
  206. Config::set('system', 'last_poller_execution', datetime_convert());
  207. }
  208. $poller_db_duration = (microtime(true) - $stamp);
  209. } else {
  210. logger("Function ".$funcname." does not exist");
  211. dba::delete('workerqueue', array('id' => $queue["id"]));
  212. }
  213. return true;
  214. }
  215. /**
  216. * @brief Execute a function from the queue
  217. *
  218. * @param array $queue Workerqueue entry
  219. * @param string $funcname name of the function
  220. * @param array $argv Array of values to be passed to the function
  221. */
  222. function poller_exec_function($queue, $funcname, $argv) {
  223. global $poller_up_start, $poller_db_duration, $poller_lock_duration;
  224. $a = get_app();
  225. $mypid = getmypid();
  226. $argc = count($argv);
  227. $new_process_id = uniqid("wrk", true);
  228. logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
  229. $stamp = (float)microtime(true);
  230. // We use the callstack here to analyze the performance of executed worker entries.
  231. // For this reason the variables have to be initialized.
  232. if (Config::get("system", "profiler")) {
  233. $a->performance["start"] = microtime(true);
  234. $a->performance["database"] = 0;
  235. $a->performance["database_write"] = 0;
  236. $a->performance["network"] = 0;
  237. $a->performance["file"] = 0;
  238. $a->performance["rendering"] = 0;
  239. $a->performance["parser"] = 0;
  240. $a->performance["marktime"] = 0;
  241. $a->performance["markstart"] = microtime(true);
  242. $a->callstack = array();
  243. }
  244. // For better logging create a new process id for every worker call
  245. // But preserve the old one for the worker
  246. $old_process_id = $a->process_id;
  247. $a->process_id = $new_process_id;
  248. $a->queue = $queue;
  249. $up_duration = number_format(microtime(true) - $poller_up_start, 3);
  250. // Reset global data to avoid interferences
  251. unset($_SESSION);
  252. $funcname($argv, $argc);
  253. $a->process_id = $old_process_id;
  254. unset($a->queue);
  255. $duration = number_format(microtime(true) - $stamp, 3);
  256. $poller_up_start = microtime(true);
  257. /* With these values we can analyze how effective the worker is.
  258. * The database and rest time should be low since this is the unproductive time.
  259. * The execution time is the productive time.
  260. * By changing parameters like the maximum number of workers we can check the effectivness.
  261. */
  262. logger('DB: '.number_format($poller_db_duration, 2).
  263. ' - Lock: '.number_format($poller_lock_duration, 2).
  264. ' - Rest: '.number_format($up_duration - $poller_db_duration - $poller_lock_duration, 2).
  265. ' - Execution: '.number_format($duration, 2), LOGGER_DEBUG);
  266. $poller_lock_duration = 0;
  267. if ($duration > 3600) {
  268. logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
  269. } elseif ($duration > 600) {
  270. logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
  271. } elseif ($duration > 300) {
  272. logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
  273. } elseif ($duration > 120) {
  274. logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
  275. }
  276. logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
  277. // Write down the performance values into the log
  278. if (Config::get("system", "profiler")) {
  279. $duration = microtime(true)-$a->performance["start"];
  280. if (Config::get("rendertime", "callstack")) {
  281. if (isset($a->callstack["database"])) {
  282. $o = "\nDatabase Read:\n";
  283. foreach ($a->callstack["database"] AS $func => $time) {
  284. $time = round($time, 3);
  285. if ($time > 0) {
  286. $o .= $func.": ".$time."\n";
  287. }
  288. }
  289. }
  290. if (isset($a->callstack["database_write"])) {
  291. $o .= "\nDatabase Write:\n";
  292. foreach ($a->callstack["database_write"] AS $func => $time) {
  293. $time = round($time, 3);
  294. if ($time > 0) {
  295. $o .= $func.": ".$time."\n";
  296. }
  297. }
  298. }
  299. if (isset($a->callstack["network"])) {
  300. $o .= "\nNetwork:\n";
  301. foreach ($a->callstack["network"] AS $func => $time) {
  302. $time = round($time, 3);
  303. if ($time > 0) {
  304. $o .= $func.": ".$time."\n";
  305. }
  306. }
  307. }
  308. } else {
  309. $o = '';
  310. }
  311. logger("ID ".$queue["id"].": ".$funcname.": ".sprintf("DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
  312. number_format($a->performance["database"] - $a->performance["database_write"], 2),
  313. number_format($a->performance["database_write"], 2),
  314. number_format($a->performance["network"], 2),
  315. number_format($a->performance["file"], 2),
  316. number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
  317. number_format($duration, 2)),
  318. LOGGER_DEBUG);
  319. }
  320. $cooldown = Config::get("system", "worker_cooldown", 0);
  321. if ($cooldown > 0) {
  322. logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
  323. sleep($cooldown);
  324. }
  325. }
  326. /**
  327. * @brief Checks if the number of database connections has reached a critical limit.
  328. *
  329. * @return bool Are more than 3/4 of the maximum connections used?
  330. */
  331. function poller_max_connections_reached() {
  332. // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
  333. $max = Config::get("system", "max_connections");
  334. // Fetch the percentage level where the poller will get active
  335. $maxlevel = Config::get("system", "max_connections_level", 75);
  336. if ($max == 0) {
  337. // the maximum number of possible user connections can be a system variable
  338. $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
  339. if (dbm::is_result($r)) {
  340. $max = $r[0]["Value"];
  341. }
  342. // Or it can be granted. This overrides the system variable
  343. $r = q("SHOW GRANTS");
  344. if (dbm::is_result($r)) {
  345. foreach ($r AS $grants) {
  346. $grant = array_pop($grants);
  347. if (stristr($grant, "GRANT USAGE ON")) {
  348. if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
  349. $max = $match[1];
  350. }
  351. }
  352. }
  353. }
  354. }
  355. // If $max is set we will use the processlist to determine the current number of connections
  356. // The processlist only shows entries of the current user
  357. if ($max != 0) {
  358. $r = q("SHOW PROCESSLIST");
  359. if (!dbm::is_result($r)) {
  360. return false;
  361. }
  362. $used = count($r);
  363. logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
  364. $level = ($used / $max) * 100;
  365. if ($level >= $maxlevel) {
  366. logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
  367. return true;
  368. }
  369. }
  370. // We will now check for the system values.
  371. // This limit could be reached although the user limits are fine.
  372. $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
  373. if (!dbm::is_result($r)) {
  374. return false;
  375. }
  376. $max = intval($r[0]["Value"]);
  377. if ($max == 0) {
  378. return false;
  379. }
  380. $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
  381. if (!dbm::is_result($r)) {
  382. return false;
  383. }
  384. $used = intval($r[0]["Value"]);
  385. if ($used == 0) {
  386. return false;
  387. }
  388. logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
  389. $level = $used / $max * 100;
  390. if ($level < $maxlevel) {
  391. return false;
  392. }
  393. logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
  394. return true;
  395. }
  396. /**
  397. * @brief fix the queue entry if the worker process died
  398. *
  399. */
  400. function poller_kill_stale_workers() {
  401. $entries = dba::select('workerqueue', array('id', 'pid', 'executed', 'priority', 'parameter'),
  402. array('`executed` > ? AND NOT `done` AND `pid` != 0', NULL_DATE),
  403. array('order' => array('priority', 'created')));
  404. while ($entry = dba::fetch($entries)) {
  405. if (!posix_kill($entry["pid"], 0)) {
  406. dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0),
  407. array('id' => $entry["id"]));
  408. } else {
  409. // Kill long running processes
  410. // Check if the priority is in a valid range
  411. if (!in_array($entry["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE))) {
  412. $entry["priority"] = PRIORITY_MEDIUM;
  413. }
  414. // Define the maximum durations
  415. $max_duration_defaults = array(PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720);
  416. $max_duration = $max_duration_defaults[$entry["priority"]];
  417. $argv = json_decode($entry["parameter"]);
  418. $argv[0] = basename($argv[0]);
  419. // How long is the process already running?
  420. $duration = (time() - strtotime($entry["executed"])) / 60;
  421. if ($duration > $max_duration) {
  422. logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
  423. posix_kill($entry["pid"], SIGTERM);
  424. // We killed the stale process.
  425. // To avoid a blocking situation we reschedule the process at the beginning of the queue.
  426. // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
  427. if ($entry["priority"] == PRIORITY_HIGH) {
  428. $new_priority = PRIORITY_MEDIUM;
  429. } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
  430. $new_priority = PRIORITY_LOW;
  431. } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
  432. $new_priority = PRIORITY_NEGLIGIBLE;
  433. }
  434. dba::update('workerqueue',
  435. array('executed' => NULL_DATE, 'created' => datetime_convert(), 'priority' => $new_priority, 'pid' => 0),
  436. array('id' => $entry["id"]));
  437. } else {
  438. logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
  439. }
  440. }
  441. }
  442. }
  443. /**
  444. * @brief Checks if the number of active workers exceeds the given limits
  445. *
  446. * @return bool Are there too much workers running?
  447. */
  448. function poller_too_much_workers() {
  449. $queues = Config::get("system", "worker_queues", 4);
  450. $maxqueues = $queues;
  451. $active = poller_active_workers();
  452. // Decrease the number of workers at higher load
  453. $load = current_load();
  454. if ($load) {
  455. $maxsysload = intval(Config::get("system", "maxloadavg", 50));
  456. $maxworkers = $queues;
  457. // Some magical mathemathics to reduce the workers
  458. $exponent = 3;
  459. $slope = $maxworkers / pow($maxsysload, $exponent);
  460. $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
  461. if (Config::get('system', 'worker_debug')) {
  462. // Create a list of queue entries grouped by their priority
  463. $listitem = array();
  464. // Adding all processes with no workerqueue entry
  465. $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
  466. (SELECT id FROM `workerqueue`
  467. WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)", getmypid());
  468. if ($process = dba::fetch($processes)) {
  469. $listitem[0] = "0:".$process["running"];
  470. }
  471. dba::close($processes);
  472. // Now adding all processes with workerqueue entries
  473. $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
  474. while ($entry = dba::fetch($entries)) {
  475. $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` WHERE `priority` = ?", $entry["priority"]);
  476. if ($process = dba::fetch($processes)) {
  477. $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
  478. }
  479. dba::close($processes);
  480. }
  481. dba::close($entries);
  482. $intervals = array(1, 10, 60);
  483. $jobs_per_minute = array();
  484. foreach ($intervals AS $interval) {
  485. $jobs = dba::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
  486. if ($job = dba::fetch($jobs)) {
  487. $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
  488. }
  489. dba::close($jobs);
  490. }
  491. $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
  492. }
  493. $entries = poller_total_entries();
  494. if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
  495. $top_priority = poller_highest_priority();
  496. $high_running = poller_process_with_priority_active($top_priority);
  497. if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
  498. logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
  499. $queues = $active + 1;
  500. }
  501. }
  502. logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
  503. // Are there fewer workers running as possible? Then fork a new one.
  504. if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
  505. logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
  506. $args = array("include/poller.php", "no_cron");
  507. get_app()->proc_run($args);
  508. }
  509. }
  510. return $active >= $queues;
  511. }
  512. /**
  513. * @brief Returns the number of active poller processes
  514. *
  515. * @return integer Number of active poller processes
  516. */
  517. function poller_active_workers() {
  518. $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'poller.php'");
  519. return $workers[0]["processes"];
  520. }
  521. /**
  522. * @brief Check if we should pass some slow processes
  523. *
  524. * When the active processes of the highest priority are using more than 2/3
  525. * of all processes, we let pass slower processes.
  526. *
  527. * @param string $highest_priority Returns the currently highest priority
  528. * @return bool We let pass a slower process than $highest_priority
  529. */
  530. function poller_passing_slow(&$highest_priority) {
  531. $highest_priority = 0;
  532. $r = q("SELECT `priority`
  533. FROM `process`
  534. INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`");
  535. // No active processes at all? Fine
  536. if (!dbm::is_result($r)) {
  537. return false;
  538. }
  539. $priorities = array();
  540. foreach ($r AS $line) {
  541. $priorities[] = $line["priority"];
  542. }
  543. // Should not happen
  544. if (count($priorities) == 0) {
  545. return false;
  546. }
  547. $highest_priority = min($priorities);
  548. // The highest process is already the slowest one?
  549. // Then we quit
  550. if ($highest_priority == PRIORITY_NEGLIGIBLE) {
  551. return false;
  552. }
  553. $high = 0;
  554. foreach ($priorities AS $priority) {
  555. if ($priority == $highest_priority) {
  556. ++$high;
  557. }
  558. }
  559. logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
  560. $passing_slow = (($high/count($priorities)) > (2/3));
  561. if ($passing_slow) {
  562. logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
  563. }
  564. return $passing_slow;
  565. }
  566. /**
  567. * @brief Find and claim the next worker process for us
  568. *
  569. * @param boolean $passing_slow Returns if we had passed low priority processes
  570. * @return boolean Have we found something?
  571. */
  572. function find_worker_processes(&$passing_slow) {
  573. $mypid = getmypid();
  574. // Check if we should pass some low priority process
  575. $highest_priority = 0;
  576. $found = false;
  577. $passing_slow = false;
  578. // The higher the number of parallel workers, the more we prefetch to prevent concurring access
  579. // We decrease the limit with the number of entries left in the queue
  580. $worker_queues = Config::get("system", "worker_queues", 4);
  581. $queue_length = Config::get('system', 'worker_fetch_limit', 1);
  582. $lower_job_limit = $worker_queues * $queue_length * 2;
  583. $jobs = poller_total_entries();
  584. // Now do some magic
  585. $exponent = 2;
  586. $slope = $queue_length / pow($lower_job_limit, $exponent);
  587. $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
  588. logger('Total: '.$jobs.' - Maximum: '.$queue_length.' - jobs per queue: '.$limit, LOGGER_DEBUG);
  589. if (poller_passing_slow($highest_priority)) {
  590. // Are there waiting processes with a higher priority than the currently highest?
  591. $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND `priority` < ? AND NOT `done`", NULL_DATE, $highest_priority),
  592. array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
  593. while ($id = dba::fetch($result)) {
  594. $ids[] = $id["id"];
  595. }
  596. dba::close($result);
  597. $found = (count($ids) > 0);
  598. if (!$found) {
  599. // Give slower processes some processing time
  600. $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND `priority` > ? AND NOT `done`", NULL_DATE, $highest_priority),
  601. array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
  602. while ($id = dba::fetch($result)) {
  603. $ids[] = $id["id"];
  604. }
  605. dba::close($result);
  606. $found = (count($ids) > 0);
  607. $passing_slow = $found;
  608. }
  609. }
  610. // If there is no result (or we shouldn't pass lower processes) we check without priority limit
  611. if (!$found) {
  612. $result = dba::select('workerqueue', array('id'), array("`executed` <= ? AND NOT `done`", NULL_DATE),
  613. array('limit' => $limit, 'order' => array('priority', 'created'), 'only_query' => true));
  614. while ($id = dba::fetch($result)) {
  615. $ids[] = $id["id"];
  616. }
  617. dba::close($result);
  618. $found = (count($ids) > 0);
  619. }
  620. if ($found) {
  621. $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
  622. array_unshift($ids, $condition);
  623. dba::update('workerqueue', array('executed' => datetime_convert(), 'pid' => $mypid), $ids);
  624. }
  625. return $found;
  626. }
  627. /**
  628. * @brief Returns the next worker process
  629. *
  630. * @param boolean $passing_slow Returns if we had passed low priority processes
  631. * @return string SQL statement
  632. */
  633. function poller_worker_process(&$passing_slow) {
  634. global $poller_db_duration, $poller_lock_duration;
  635. $stamp = (float)microtime(true);
  636. // There can already be jobs for us in the queue.
  637. $r = q("SELECT * FROM `workerqueue` WHERE `pid` = %d AND NOT `done`", intval(getmypid()));
  638. if (dbm::is_result($r)) {
  639. $poller_db_duration += (microtime(true) - $stamp);
  640. return $r;
  641. }
  642. $stamp = (float)microtime(true);
  643. if (!Lock::set('poller_worker_process')) {
  644. return false;
  645. }
  646. $poller_lock_duration = (microtime(true) - $stamp);
  647. $stamp = (float)microtime(true);
  648. $found = find_worker_processes($passing_slow);
  649. $poller_db_duration += (microtime(true) - $stamp);
  650. Lock::remove('poller_worker_process');
  651. if ($found) {
  652. $r = q("SELECT * FROM `workerqueue` WHERE `pid` = %d AND NOT `done`", intval(getmypid()));
  653. }
  654. return $r;
  655. }
  656. /**
  657. * @brief Removes a workerqueue entry from the current process
  658. */
  659. function poller_unclaim_process() {
  660. $mypid = getmypid();
  661. dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0), array('pid' => $mypid, 'done' => false));
  662. }
  663. /**
  664. * @brief Call the front end worker
  665. */
  666. function call_worker() {
  667. if (!Config::get("system", "frontend_worker")) {
  668. return;
  669. }
  670. $url = System::baseUrl()."/worker";
  671. fetch_url($url, false, $redirects, 1);
  672. }
  673. /**
  674. * @brief Call the front end worker if there aren't any active
  675. */
  676. function call_worker_if_idle() {
  677. if (!Config::get("system", "frontend_worker")) {
  678. return;
  679. }
  680. // Do we have "proc_open"? Then we can fork the poller
  681. if (function_exists("proc_open")) {
  682. // When was the last time that we called the worker?
  683. // Less than one minute? Then we quit
  684. if ((time() - Config::get("system", "worker_started")) < 60) {
  685. return;
  686. }
  687. set_config("system", "worker_started", time());
  688. // Do we have enough running workers? Then we quit here.
  689. if (poller_too_much_workers()) {
  690. // Cleaning dead processes
  691. poller_kill_stale_workers();
  692. get_app()->remove_inactive_processes();
  693. return;
  694. }
  695. poller_run_cron();
  696. logger('Call poller', LOGGER_DEBUG);
  697. $args = array("include/poller.php", "no_cron");
  698. get_app()->proc_run($args);
  699. return;
  700. }
  701. // We cannot execute background processes.
  702. // We now run the processes from the frontend.
  703. // This won't work with long running processes.
  704. poller_run_cron();
  705. clear_worker_processes();
  706. $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
  707. if ($workers[0]["processes"] == 0) {
  708. call_worker();
  709. }
  710. }
  711. /**
  712. * @brief Removes long running worker processes
  713. */
  714. function clear_worker_processes() {
  715. $timeout = Config::get("system", "frontend_worker_timeout", 10);
  716. /// @todo We should clean up the corresponding workerqueue entries as well
  717. q("DELETE FROM `process` WHERE `created` < '%s' AND `command` = 'worker.php'",
  718. dbesc(datetime_convert('UTC','UTC',"now - ".$timeout." minutes")));
  719. }
  720. /**
  721. * @brief Runs the cron processes
  722. */
  723. function poller_run_cron() {
  724. logger('Add cron entries', LOGGER_DEBUG);
  725. // Check for spooled items
  726. proc_run(PRIORITY_HIGH, "include/spool_post.php");
  727. // Run the cron job that calls all other jobs
  728. proc_run(PRIORITY_MEDIUM, "include/cron.php");
  729. // Run the cronhooks job separately from cron for being able to use a different timing
  730. proc_run(PRIORITY_MEDIUM, "include/cronhooks.php");
  731. // Cleaning dead processes
  732. poller_kill_stale_workers();
  733. }
  734. if (array_search(__file__,get_included_files())===0) {
  735. poller_run($_SERVER["argv"],$_SERVER["argc"]);
  736. poller_unclaim_process();
  737. get_app()->end_process();
  738. killme();
  739. }