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