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