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