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.

580 lines
16KB

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