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