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