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