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