Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

904 lignes
28 KiB

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