]> git.mxchange.org Git - friendica.git/blob - src/Core/Worker.php
96e4a5bb16f9cc0d6a84174e0e43945ac1b2ec67
[friendica.git] / src / Core / Worker.php
1 <?php
2 /**
3  * @file src/Core/Worker.php
4  */
5 namespace Friendica\Core;
6
7 use Friendica\App;
8 use Friendica\Core\System;
9 use Friendica\Core\Config;
10 use Friendica\Core\Worker;
11 use Friendica\Database\DBM;
12 use Friendica\Util\Lock;
13
14 use dba;
15
16 require_once 'include/dba.php';
17
18 /**
19  * @file src/Core/Worker.php
20  *
21  * @brief Contains the class for the worker background job processing
22  */
23
24 /**
25  * @brief Worker methods
26  */
27 class Worker
28 {
29         private static $up_start;
30         private static $db_duration;
31         private static $last_update;
32         private static $lock_duration;
33
34         /**
35          * @brief Processes the tasks that are in the workerqueue table
36          *
37          * @param boolean $run_cron Should the cron processes be executed?
38          * @return void
39          */
40         public static function processQueue($run_cron = true)
41         {
42                 $a = get_app();
43
44                 self::$up_start = microtime(true);
45
46                 // At first check the maximum load. We shouldn't continue with a high load
47                 if ($a->maxload_reached()) {
48                         logger('Pre check: maximum load reached, quitting.', LOGGER_DEBUG);
49                         return;
50                 }
51
52                 // We now start the process. This is done after the load check since this could increase the load.
53                 $a->start_process();
54
55                 // Kill stale processes every 5 minutes
56                 $last_cleanup = Config::get('system', 'poller_last_cleaned', 0);
57                 if (time() > ($last_cleanup + 300)) {
58                         Config::set('system', 'poller_last_cleaned', time());
59                         self::killStaleWorkers();
60                 }
61
62                 // Count active workers and compare them with a maximum value that depends on the load
63                 if (self::tooMuchWorkers()) {
64                         logger('Pre check: Active worker limit reached, quitting.', LOGGER_DEBUG);
65                         return;
66                 }
67
68                 // Do we have too few memory?
69                 if ($a->min_memory_reached()) {
70                         logger('Pre check: Memory limit reached, quitting.', LOGGER_DEBUG);
71                         return;
72                 }
73
74                 // Possibly there are too much database connections
75                 if (self::maxConnectionsReached()) {
76                         logger('Pre check: maximum connections reached, quitting.', LOGGER_DEBUG);
77                         return;
78                 }
79
80                 // Possibly there are too much database processes that block the system
81                 if ($a->max_processes_reached()) {
82                         logger('Pre check: maximum processes reached, quitting.', LOGGER_DEBUG);
83                         return;
84                 }
85
86                 // Now we start additional cron processes if we should do so
87                 if ($run_cron) {
88                         self::runCron();
89                 }
90
91                 $starttime = time();
92
93                 // We fetch the next queue entry that is about to be executed
94                 while ($r = self::workerProcess($passing_slow)) {
95                         // When we are processing jobs with a lower priority, we don't refetch new jobs
96                         // Otherwise fast jobs could wait behind slow ones and could be blocked.
97                         $refetched = $passing_slow;
98
99                         foreach ($r as $entry) {
100                                 // Assure that the priority is an integer value
101                                 $entry['priority'] = (int)$entry['priority'];
102
103                                 // The work will be done
104                                 if (!self::execute($entry)) {
105                                         logger('Process execution failed, quitting.', LOGGER_DEBUG);
106                                         return;
107                                 }
108
109                                 // If possible we will fetch new jobs for this worker
110                                 if (!$refetched && Lock::set('poller_worker_process', 0)) {
111                                         $stamp = (float)microtime(true);
112                                         $refetched = self::findWorkerProcesses($passing_slow);
113                                         self::$db_duration += (microtime(true) - $stamp);
114                                         Lock::remove('poller_worker_process');
115                                 }
116                         }
117
118                         // To avoid the quitting of multiple workers only one worker at a time will execute the check
119                         if (Lock::set('poller_worker', 0)) {
120                                 $stamp = (float)microtime(true);
121                                 // Count active workers and compare them with a maximum value that depends on the load
122                                 if (self::tooMuchWorkers()) {
123                                         logger('Active worker limit reached, quitting.', LOGGER_DEBUG);
124                                         return;
125                                 }
126
127                                 // Check free memory
128                                 if ($a->min_memory_reached()) {
129                                         logger('Memory limit reached, quitting.', LOGGER_DEBUG);
130                                         return;
131                                 }
132                                 Lock::remove('poller_worker');
133                                 self::$db_duration += (microtime(true) - $stamp);
134                         }
135
136                         // Quit the worker once every 5 minutes
137                         if (time() > ($starttime + 300)) {
138                                 logger('Process lifetime reached, quitting.', LOGGER_DEBUG);
139                                 return;
140                         }
141                 }
142                 logger("Couldn't select a workerqueue entry, quitting.", LOGGER_DEBUG);
143         }
144
145         /**
146          * @brief Returns the number of non executed entries in the worker queue
147          *
148          * @return integer Number of non executed entries in the worker queue
149          */
150         private static function totalEntries()
151         {
152                 $s = dba::fetch_first("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` <= ? AND NOT `done`", NULL_DATE);
153                 if (DBM::is_result($s)) {
154                         return $s["total"];
155                 } else {
156                         return 0;
157                 }
158         }
159
160         /**
161          * @brief Returns the highest priority in the worker queue that isn't executed
162          *
163          * @return integer Number of active worker processes
164          */
165         private static function highestPriority()
166         {
167                 $condition = array("`executed` <= ? AND NOT `done`", NULL_DATE);
168                 $s = dba::selectFirst('workerqueue', ['priority'], $condition, ['order' => ['priority']]);
169                 if (DBM::is_result($s)) {
170                         return $s["priority"];
171                 } else {
172                         return 0;
173                 }
174         }
175
176         /**
177          * @brief Returns if a process with the given priority is running
178          *
179          * @param integer $priority The priority that should be checked
180          *
181          * @return integer Is there a process running with that priority?
182          */
183         private static function processWithPriorityActive($priority)
184         {
185                 $condition = array("`priority` <= ? AND `executed` > ? AND NOT `done`", $priority, NULL_DATE);
186                 return dba::exists('workerqueue', $condition);
187         }
188
189         /**
190          * @brief Execute a worker entry
191          *
192          * @param array $queue Workerqueue entry
193          *
194          * @return boolean "true" if further processing should be stopped
195          */
196         public static function execute($queue)
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 (self::maxConnectionsReached()) {
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 (method_exists(sprintf('Friendica\Worker\%s', $include), 'execute')) {
226                         // We constantly update the "executed" date every minute to avoid being killed too soon
227                         if (!isset(self::$last_update)) {
228                                 self::$last_update = strtotime($queue["executed"]);
229                         }
230
231                         $age = (time() - self::$last_update) / 60;
232                         self::$last_update = time();
233
234                         if ($age > 1) {
235                                 $stamp = (float)microtime(true);
236                                 dba::update('workerqueue', array('executed' => datetime_convert()), array('pid' => $mypid, 'done' => false));
237                                 self::$db_duration += (microtime(true) - $stamp);
238                         }
239
240                         array_shift($argv);
241
242                         self::execFunction($queue, $include, $argv, true);
243
244                         $stamp = (float)microtime(true);
245                         if (dba::update('workerqueue', array('done' => true), array('id' => $queue["id"]))) {
246                                 Config::set('system', 'last_poller_execution', datetime_convert());
247                         }
248                         self::$db_duration = (microtime(true) - $stamp);
249
250                         return true;
251                 }
252
253                 // The script could be provided as full path or only with the function name
254                 if ($include == basename($include)) {
255                         $include = "include/".$include.".php";
256                 }
257
258                 if (!validate_include($include)) {
259                         logger("Include file ".$argv[0]." is not valid!");
260                         dba::delete('workerqueue', array('id' => $queue["id"]));
261                         return true;
262                 }
263
264                 require_once $include;
265
266                 $funcname = str_replace(".php", "", basename($argv[0]))."_run";
267
268                 if (function_exists($funcname)) {
269                         // We constantly update the "executed" date every minute to avoid being killed too soon
270                         if (!isset(self::$last_update)) {
271                                 self::$last_update = strtotime($queue["executed"]);
272                         }
273
274                         $age = (time() - self::$last_update) / 60;
275                         self::$last_update = time();
276
277                         if ($age > 1) {
278                                 $stamp = (float)microtime(true);
279                                 dba::update('workerqueue', array('executed' => datetime_convert()), array('pid' => $mypid, 'done' => false));
280                                 self::$db_duration += (microtime(true) - $stamp);
281                         }
282
283                         self::execFunction($queue, $funcname, $argv, false);
284
285                         $stamp = (float)microtime(true);
286                         if (dba::update('workerqueue', array('done' => true), array('id' => $queue["id"]))) {
287                                 Config::set('system', 'last_poller_execution', datetime_convert());
288                         }
289                         self::$db_duration = (microtime(true) - $stamp);
290                 } else {
291                         logger("Function ".$funcname." does not exist");
292                         dba::delete('workerqueue', array('id' => $queue["id"]));
293                 }
294
295                 return true;
296         }
297
298         /**
299          * @brief Execute a function from the queue
300          *
301          * @param array   $queue       Workerqueue entry
302          * @param string  $funcname    name of the function
303          * @param array   $argv        Array of values to be passed to the function
304          * @param boolean $method_call boolean
305          * @return void
306          */
307         private static function execFunction($queue, $funcname, $argv, $method_call)
308         {
309                 $a = get_app();
310
311                 $mypid = getmypid();
312
313                 $argc = count($argv);
314
315                 $new_process_id = uniqid("wrk", true);
316
317                 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
318
319                 $stamp = (float)microtime(true);
320
321                 // We use the callstack here to analyze the performance of executed worker entries.
322                 // For this reason the variables have to be initialized.
323                 if (Config::get("system", "profiler")) {
324                         $a->performance["start"] = microtime(true);
325                         $a->performance["database"] = 0;
326                         $a->performance["database_write"] = 0;
327                         $a->performance["network"] = 0;
328                         $a->performance["file"] = 0;
329                         $a->performance["rendering"] = 0;
330                         $a->performance["parser"] = 0;
331                         $a->performance["marktime"] = 0;
332                         $a->performance["markstart"] = microtime(true);
333                         $a->callstack = array();
334                 }
335
336                 // For better logging create a new process id for every worker call
337                 // But preserve the old one for the worker
338                 $old_process_id = $a->process_id;
339                 $a->process_id = $new_process_id;
340                 $a->queue = $queue;
341
342                 $up_duration = number_format(microtime(true) - self::$up_start, 3);
343
344                 // Reset global data to avoid interferences
345                 unset($_SESSION);
346
347                 if ($method_call) {
348                         call_user_func_array(sprintf('Friendica\Worker\%s::execute', $funcname), $argv);
349                 } else {
350                         $funcname($argv, $argc);
351                 }
352
353                 $a->process_id = $old_process_id;
354                 unset($a->queue);
355
356                 $duration = number_format(microtime(true) - $stamp, 3);
357
358                 self::$up_start = microtime(true);
359
360                 /* With these values we can analyze how effective the worker is.
361                  * The database and rest time should be low since this is the unproductive time.
362                  * The execution time is the productive time.
363                  * By changing parameters like the maximum number of workers we can check the effectivness.
364                 */
365                 logger(
366                         'DB: '.number_format(self::$db_duration, 2).
367                         ' - Lock: '.number_format(self::$lock_duration, 2).
368                         ' - Rest: '.number_format($up_duration - self::$db_duration - self::$lock_duration, 2).
369                         ' - Execution: '.number_format($duration, 2),
370                         LOGGER_DEBUG
371                 );
372
373                 self::$lock_duration = 0;
374
375                 if ($duration > 3600) {
376                         logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
377                 } elseif ($duration > 600) {
378                         logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
379                 } elseif ($duration > 300) {
380                         logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
381                 } elseif ($duration > 120) {
382                         logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
383                 }
384
385                 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds. Process PID: ".$new_process_id);
386
387                 // Write down the performance values into the log
388                 if (Config::get("system", "profiler")) {
389                         $duration = microtime(true)-$a->performance["start"];
390
391                         if (Config::get("rendertime", "callstack")) {
392                                 if (isset($a->callstack["database"])) {
393                                         $o = "\nDatabase Read:\n";
394                                         foreach ($a->callstack["database"] as $func => $time) {
395                                                 $time = round($time, 3);
396                                                 if ($time > 0) {
397                                                         $o .= $func.": ".$time."\n";
398                                                 }
399                                         }
400                                 }
401                                 if (isset($a->callstack["database_write"])) {
402                                         $o .= "\nDatabase Write:\n";
403                                         foreach ($a->callstack["database_write"] as $func => $time) {
404                                                 $time = round($time, 3);
405                                                 if ($time > 0) {
406                                                         $o .= $func.": ".$time."\n";
407                                                 }
408                                         }
409                                 }
410                                 if (isset($a->callstack["network"])) {
411                                         $o .= "\nNetwork:\n";
412                                         foreach ($a->callstack["network"] as $func => $time) {
413                                                 $time = round($time, 3);
414                                                 if ($time > 0) {
415                                                         $o .= $func.": ".$time."\n";
416                                                 }
417                                         }
418                                 }
419                         } else {
420                                 $o = '';
421                         }
422
423                         logger(
424                                 "ID ".$queue["id"].": ".$funcname.": ".sprintf(
425                                         "DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
426                                         number_format($a->performance["database"] - $a->performance["database_write"], 2),
427                                         number_format($a->performance["database_write"], 2),
428                                         number_format($a->performance["network"], 2),
429                                         number_format($a->performance["file"], 2),
430                                         number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
431                                         number_format($duration, 2)
432                                 ),
433                                 LOGGER_DEBUG
434                         );
435                 }
436
437                 $cooldown = Config::get("system", "worker_cooldown", 0);
438
439                 if ($cooldown > 0) {
440                         logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
441                         sleep($cooldown);
442                 }
443         }
444
445         /**
446          * @brief Checks if the number of database connections has reached a critical limit.
447          *
448          * @return bool Are more than 3/4 of the maximum connections used?
449          */
450         private static function maxConnectionsReached()
451         {
452                 // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
453                 $max = Config::get("system", "max_connections");
454
455                 // Fetch the percentage level where the worker will get active
456                 $maxlevel = Config::get("system", "max_connections_level", 75);
457
458                 if ($max == 0) {
459                         // the maximum number of possible user connections can be a system variable
460                         $r = dba::fetch_first("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
461                         if (DBM::is_result($r)) {
462                                 $max = $r["Value"];
463                         }
464                         // Or it can be granted. This overrides the system variable
465                         $r = dba::p('SHOW GRANTS');
466                         while ($grants = dba::fetch($r)) {
467                                 $grant = array_pop($grants);
468                                 if (stristr($grant, "GRANT USAGE ON")) {
469                                         if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
470                                                 $max = $match[1];
471                                         }
472                                 }
473                         }
474                         dba::close($r);
475                 }
476
477                 // If $max is set we will use the processlist to determine the current number of connections
478                 // The processlist only shows entries of the current user
479                 if ($max != 0) {
480                         $r = dba::p('SHOW PROCESSLIST');
481                         $used = dba::num_rows($r);
482                         dba::close($r);
483
484                         logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
485
486                         $level = ($used / $max) * 100;
487
488                         if ($level >= $maxlevel) {
489                                 logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
490                                 return true;
491                         }
492                 }
493
494                 // We will now check for the system values.
495                 // This limit could be reached although the user limits are fine.
496                 $r = dba::fetch_first("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
497                 if (!DBM::is_result($r)) {
498                         return false;
499                 }
500                 $max = intval($r["Value"]);
501                 if ($max == 0) {
502                         return false;
503                 }
504                 $r = dba::fetch_first("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
505                 if (!DBM::is_result($r)) {
506                         return false;
507                 }
508                 $used = intval($r["Value"]);
509                 if ($used == 0) {
510                         return false;
511                 }
512                 logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
513
514                 $level = $used / $max * 100;
515
516                 if ($level < $maxlevel) {
517                         return false;
518                 }
519                 logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
520                 return true;
521         }
522
523         /**
524          * @brief fix the queue entry if the worker process died
525          * @return void
526          */
527         private static function killStaleWorkers()
528         {
529                 $entries = dba::select(
530                         'workerqueue',
531                         array('id', 'pid', 'executed', 'priority', 'parameter'),
532                         array('`executed` > ? AND NOT `done` AND `pid` != 0', NULL_DATE),
533                         array('order' => array('priority', 'created'))
534                 );
535
536                 while ($entry = dba::fetch($entries)) {
537                         if (!posix_kill($entry["pid"], 0)) {
538                                 dba::update(
539                                         'workerqueue',
540                                         array('executed' => NULL_DATE, 'pid' => 0),
541                                         array('id' => $entry["id"])
542                                 );
543                         } else {
544                                 // Kill long running processes
545                                 // Check if the priority is in a valid range
546                                 if (!in_array($entry["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE))) {
547                                         $entry["priority"] = PRIORITY_MEDIUM;
548                                 }
549
550                                 // Define the maximum durations
551                                 $max_duration_defaults = array(PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720);
552                                 $max_duration = $max_duration_defaults[$entry["priority"]];
553
554                                 $argv = json_decode($entry["parameter"]);
555                                 $argv[0] = basename($argv[0]);
556
557                                 // How long is the process already running?
558                                 $duration = (time() - strtotime($entry["executed"])) / 60;
559                                 if ($duration > $max_duration) {
560                                         logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
561                                         posix_kill($entry["pid"], SIGTERM);
562
563                                         // We killed the stale process.
564                                         // To avoid a blocking situation we reschedule the process at the beginning of the queue.
565                                         // Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
566                                         if ($entry["priority"] == PRIORITY_HIGH) {
567                                                 $new_priority = PRIORITY_MEDIUM;
568                                         } elseif ($entry["priority"] == PRIORITY_MEDIUM) {
569                                                 $new_priority = PRIORITY_LOW;
570                                         } elseif ($entry["priority"] != PRIORITY_CRITICAL) {
571                                                 $new_priority = PRIORITY_NEGLIGIBLE;
572                                         }
573                                         dba::update(
574                                                 'workerqueue',
575                                                 array('executed' => NULL_DATE, 'created' => datetime_convert(), 'priority' => $new_priority, 'pid' => 0),
576                                                 array('id' => $entry["id"])
577                                         );
578                                 } else {
579                                         logger("Worker process ".$entry["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
580                                 }
581                         }
582                 }
583         }
584
585         /**
586          * @brief Checks if the number of active workers exceeds the given limits
587          *
588          * @return bool Are there too much workers running?
589          */
590         public static function tooMuchWorkers()
591         {
592                 $queues = Config::get("system", "worker_queues", 4);
593
594                 $maxqueues = $queues;
595
596                 $active = self::activeWorkers();
597
598                 // Decrease the number of workers at higher load
599                 $load = current_load();
600                 if ($load) {
601                         $maxsysload = intval(Config::get("system", "maxloadavg", 50));
602
603                         $maxworkers = $queues;
604
605                         // Some magical mathemathics to reduce the workers
606                         $exponent = 3;
607                         $slope = $maxworkers / pow($maxsysload, $exponent);
608                         $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
609                         $processlist = '';
610
611                         if (Config::get('system', 'worker_debug')) {
612                                 // Create a list of queue entries grouped by their priority
613                                 $listitem = array();
614
615                                 // Adding all processes with no workerqueue entry
616                                 $processes = dba::p(
617                                         "SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS
618                                                         (SELECT id FROM `workerqueue`
619                                                         WHERE `workerqueue`.`pid` = `process`.`pid` AND NOT `done` AND `pid` != ?)",
620                                         getmypid()
621                                 );
622
623                                 if ($process = dba::fetch($processes)) {
624                                         $listitem[0] = "0:".$process["running"];
625                                 }
626                                 dba::close($processes);
627
628                                 // Now adding all processes with workerqueue entries
629                                 $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` WHERE NOT `done` GROUP BY `priority`");
630                                 while ($entry = dba::fetch($entries)) {
631                                         $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done` WHERE `priority` = ?", $entry["priority"]);
632                                         if ($process = dba::fetch($processes)) {
633                                                 $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
634                                         }
635                                         dba::close($processes);
636                                 }
637                                 dba::close($entries);
638
639                                 $intervals = array(1, 10, 60);
640                                 $jobs_per_minute = array();
641                                 foreach ($intervals as $interval) {
642                                         $jobs = dba::p("SELECT COUNT(*) AS `jobs` FROM `workerqueue` WHERE `done` AND `executed` > UTC_TIMESTAMP() - INTERVAL ".intval($interval)." MINUTE");
643                                         if ($job = dba::fetch($jobs)) {
644                                                 $jobs_per_minute[$interval] = number_format($job['jobs'] / $interval, 0);
645                                         }
646                                         dba::close($jobs);
647                                 }
648                                 $processlist = ' - jpm: '.implode('/', $jobs_per_minute).' ('.implode(', ', $listitem).')';
649                         }
650
651                         $entries = self::totalEntries();
652
653                         if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
654                                 $top_priority = self::highestPriority();
655                                 $high_running = self::processWithPriorityActive($top_priority);
656
657                                 if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
658                                         logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
659                                         $queues = $active + 1;
660                                 }
661                         }
662
663                         logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
664
665                         // Are there fewer workers running as possible? Then fork a new one.
666                         if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
667                                 logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
668                                 self::spawnWorker();
669                         }
670                 }
671
672                 return $active >= $queues;
673         }
674
675         /**
676          * @brief Returns the number of active worker processes
677          *
678          * @return integer Number of active worker processes
679          */
680         private static function activeWorkers()
681         {
682                 $workers = dba::fetch_first("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'Worker.php'");
683
684                 return $workers["processes"];
685         }
686
687         /**
688          * @brief Check if we should pass some slow processes
689          *
690          * When the active processes of the highest priority are using more than 2/3
691          * of all processes, we let pass slower processes.
692          *
693          * @param string $highest_priority Returns the currently highest priority
694          * @return bool We let pass a slower process than $highest_priority
695          */
696         private static function passingSlow(&$highest_priority)
697         {
698                 $highest_priority = 0;
699
700                 $r = dba::p(
701                         "SELECT `priority`
702                                 FROM `process`
703                                 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` AND NOT `done`"
704                 );
705
706                 // No active processes at all? Fine
707                 if (!DBM::is_result($r)) {
708                         return false;
709                 }
710                 $priorities = array();
711                 while ($line = dba::fetch($r)) {
712                         $priorities[] = $line["priority"];
713                 }
714                 dba::close($r);
715
716                 // Should not happen
717                 if (count($priorities) == 0) {
718                         return false;
719                 }
720                 $highest_priority = min($priorities);
721
722                 // The highest process is already the slowest one?
723                 // Then we quit
724                 if ($highest_priority == PRIORITY_NEGLIGIBLE) {
725                         return false;
726                 }
727                 $high = 0;
728                 foreach ($priorities as $priority) {
729                         if ($priority == $highest_priority) {
730                                 ++$high;
731                         }
732                 }
733                 logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
734                 $passing_slow = (($high/count($priorities)) > (2/3));
735
736                 if ($passing_slow) {
737                         logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
738                 }
739                 return $passing_slow;
740         }
741
742         /**
743          * @brief Find and claim the next worker process for us
744          *
745          * @param boolean $passing_slow Returns if we had passed low priority processes
746          * @return boolean Have we found something?
747          */
748         private static function findWorkerProcesses(&$passing_slow)
749         {
750                 $mypid = getmypid();
751
752                 // Check if we should pass some low priority process
753                 $highest_priority = 0;
754                 $found = false;
755                 $passing_slow = false;
756
757                 // The higher the number of parallel workers, the more we prefetch to prevent concurring access
758                 // We decrease the limit with the number of entries left in the queue
759                 $worker_queues = Config::get("system", "worker_queues", 4);
760                 $queue_length = Config::get('system', 'worker_fetch_limit', 1);
761                 $lower_job_limit = $worker_queues * $queue_length * 2;
762                 $jobs = self::totalEntries();
763
764                 // Now do some magic
765                 $exponent = 2;
766                 $slope = $queue_length / pow($lower_job_limit, $exponent);
767                 $limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
768
769                 logger('Total: '.$jobs.' - Maximum: '.$queue_length.' - jobs per queue: '.$limit, LOGGER_DEBUG);
770
771                 if (self::passingSlow($highest_priority)) {
772                         // Are there waiting processes with a higher priority than the currently highest?
773                         $result = dba::select(
774                                 'workerqueue',
775                                 ['id'],
776                                 ["`executed` <= ? AND `priority` < ? AND NOT `done`", NULL_DATE, $highest_priority],
777                                 ['limit' => $limit, 'order' => ['priority', 'created']]
778                         );
779
780                         while ($id = dba::fetch($result)) {
781                                 $ids[] = $id["id"];
782                         }
783                         dba::close($result);
784
785                         $found = (count($ids) > 0);
786
787                         if (!$found) {
788                                 // Give slower processes some processing time
789                                 $result = dba::select(
790                                         'workerqueue',
791                                         ['id'],
792                                         ["`executed` <= ? AND `priority` > ? AND NOT `done`", NULL_DATE, $highest_priority],
793                                         ['limit' => $limit, 'order' => ['priority', 'created']]
794                                 );
795
796                                 while ($id = dba::fetch($result)) {
797                                         $ids[] = $id["id"];
798                                 }
799                                 dba::close($result);
800
801                                 $found = (count($ids) > 0);
802                                 $passing_slow = $found;
803                         }
804                 }
805
806                 // If there is no result (or we shouldn't pass lower processes) we check without priority limit
807                 if (!$found) {
808                         $result = dba::select(
809                                 'workerqueue',
810                                 ['id'],
811                                 ["`executed` <= ? AND NOT `done`", NULL_DATE],
812                                 ['limit' => $limit, 'order' => ['priority', 'created']]
813                         );
814
815                         while ($id = dba::fetch($result)) {
816                                 $ids[] = $id["id"];
817                         }
818                         dba::close($result);
819
820                         $found = (count($ids) > 0);
821                 }
822
823                 if ($found) {
824                         $condition = "`id` IN (".substr(str_repeat("?, ", count($ids)), 0, -2).") AND `pid` = 0 AND NOT `done`";
825                         array_unshift($ids, $condition);
826                         dba::update('workerqueue', array('executed' => datetime_convert(), 'pid' => $mypid), $ids);
827                 }
828
829                 return $found;
830         }
831
832         /**
833          * @brief Returns the next worker process
834          *
835          * @param boolean $passing_slow Returns if we had passed low priority processes
836          * @return string SQL statement
837          */
838         public static function workerProcess(&$passing_slow)
839         {
840                 $stamp = (float)microtime(true);
841
842                 // There can already be jobs for us in the queue.
843                 $r = dba::select('workerqueue', array(), array('pid' => getmypid(), 'done' => false));
844                 if (DBM::is_result($r)) {
845                         self::$db_duration += (microtime(true) - $stamp);
846                         return dba::inArray($r);
847                 }
848                 dba::close($r);
849
850                 $stamp = (float)microtime(true);
851                 if (!Lock::set('poller_worker_process')) {
852                         return false;
853                 }
854                 self::$lock_duration = (microtime(true) - $stamp);
855
856                 $stamp = (float)microtime(true);
857                 $found = self::findWorkerProcesses($passing_slow);
858                 self::$db_duration += (microtime(true) - $stamp);
859
860                 Lock::remove('poller_worker_process');
861
862                 if ($found) {
863                         $r = dba::select('workerqueue', array(), array('pid' => getmypid(), 'done' => false));
864                         return dba::inArray($r);
865                 }
866                 return false;
867         }
868
869         /**
870          * @brief Removes a workerqueue entry from the current process
871          * @return void
872          */
873         public static function unclaimProcess()
874         {
875                 $mypid = getmypid();
876
877                 dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0), array('pid' => $mypid, 'done' => false));
878         }
879
880         /**
881          * @brief Call the front end worker
882          * @return void
883          */
884         public static function callWorker()
885         {
886                 if (!Config::get("system", "frontend_worker")) {
887                         return;
888                 }
889
890                 $url = System::baseUrl()."/worker";
891                 fetch_url($url, false, $redirects, 1);
892         }
893
894         /**
895          * @brief Call the front end worker if there aren't any active
896          * @return void
897          */
898         public static function executeIfIdle()
899         {
900                 if (!Config::get("system", "frontend_worker")) {
901                         return;
902                 }
903
904                 // Do we have "proc_open"? Then we can fork the worker
905                 if (function_exists("proc_open")) {
906                         // When was the last time that we called the worker?
907                         // Less than one minute? Then we quit
908                         if ((time() - Config::get("system", "worker_started")) < 60) {
909                                 return;
910                         }
911
912                         Config::set("system", "worker_started", time());
913
914                         // Do we have enough running workers? Then we quit here.
915                         if (self::tooMuchWorkers()) {
916                                 // Cleaning dead processes
917                                 self::killStaleWorkers();
918                                 get_app()->remove_inactive_processes();
919
920                                 return;
921                         }
922
923                         self::runCron();
924
925                         logger('Call worker', LOGGER_DEBUG);
926                         self::spawnWorker();
927                         return;
928                 }
929
930                 // We cannot execute background processes.
931                 // We now run the processes from the frontend.
932                 // This won't work with long running processes.
933                 self::runCron();
934
935                 self::clearProcesses();
936
937                 $workers = dba::fetch_first("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
938
939                 if ($workers["processes"] == 0) {
940                         self::callWorker();
941                 }
942         }
943
944         /**
945          * @brief Removes long running worker processes
946          * @return void
947          */
948         public static function clearProcesses()
949         {
950                 $timeout = Config::get("system", "frontend_worker_timeout", 10);
951
952                 /// @todo We should clean up the corresponding workerqueue entries as well
953                 $condition = array("`created` < ? AND `command` = 'worker.php'",
954                                 datetime_convert('UTC', 'UTC', "now - ".$timeout." minutes"));
955                 dba::delete('process', $condition);
956         }
957
958         /**
959          * @brief Runs the cron processes
960          * @return void
961          */
962         private static function runCron()
963         {
964                 logger('Add cron entries', LOGGER_DEBUG);
965
966                 // Check for spooled items
967                 self::add(PRIORITY_HIGH, "SpoolPost");
968
969                 // Run the cron job that calls all other jobs
970                 self::add(PRIORITY_MEDIUM, "Cron");
971
972                 // Run the cronhooks job separately from cron for being able to use a different timing
973                 self::add(PRIORITY_MEDIUM, "CronHooks");
974
975                 // Cleaning dead processes
976                 self::killStaleWorkers();
977         }
978
979         /**
980          * @return void
981          */
982         public static function spawnWorker()
983         {
984                 $args = array("scripts/worker.php", "no_cron");
985                 get_app()->proc_run($args);
986         }
987
988         /**
989          * @brief Adds tasks to the worker queue
990          *
991          * @param (integer|array) priority or parameter array, strings are deprecated and are ignored
992          *
993          * next args are passed as $cmd command line
994          * or: Worker::add(PRIORITY_HIGH, "Notifier", "drop", $drop_id);
995          * or: Worker::add(array('priority' => PRIORITY_HIGH, 'dont_fork' => true), "CreateShadowEntry", $post_id);
996          *
997          * @note $cmd and string args are surrounded with ""
998          *
999          * @hooks 'proc_run'
1000          *      array $arr
1001          *
1002          * @return boolean "false" if proc_run couldn't be executed
1003          */
1004         public static function add($cmd)
1005         {
1006                 $proc_args = func_get_args();
1007
1008                 $args = array();
1009                 if (!count($proc_args)) {
1010                         return false;
1011                 }
1012
1013                 // Preserve the first parameter
1014                 // It could contain a command, the priority or an parameter array
1015                 // If we use the parameter array we have to protect it from the following function
1016                 $run_parameter = array_shift($proc_args);
1017
1018                 // expand any arrays
1019                 foreach ($proc_args as $arg) {
1020                         if (is_array($arg)) {
1021                                 foreach ($arg as $n) {
1022                                         $args[] = $n;
1023                                 }
1024                         } else {
1025                                 $args[] = $arg;
1026                         }
1027                 }
1028
1029                 // Now we add the run parameters back to the array
1030                 array_unshift($args, $run_parameter);
1031
1032                 $arr = array('args' => $args, 'run_cmd' => true);
1033
1034                 call_hooks("proc_run", $arr);
1035                 if (!$arr['run_cmd'] || !count($args)) {
1036                         return true;
1037                 }
1038
1039                 $priority = PRIORITY_MEDIUM;
1040                 $dont_fork = Config::get("system", "worker_dont_fork");
1041                 $created = datetime_convert();
1042
1043                 if (is_int($run_parameter)) {
1044                         $priority = $run_parameter;
1045                 } elseif (is_array($run_parameter)) {
1046                         if (isset($run_parameter['priority'])) {
1047                                 $priority = $run_parameter['priority'];
1048                         }
1049                         if (isset($run_parameter['created'])) {
1050                                 $created = $run_parameter['created'];
1051                         }
1052                         if (isset($run_parameter['dont_fork'])) {
1053                                 $dont_fork = $run_parameter['dont_fork'];
1054                         }
1055                 }
1056
1057                 $argv = $args;
1058                 array_shift($argv);
1059
1060                 $parameters = json_encode($argv);
1061                 $found = dba::exists('workerqueue', array('parameter' => $parameters, 'done' => false));
1062
1063                 // Quit if there was a database error - a precaution for the update process to 3.5.3
1064                 if (dba::errorNo() != 0) {
1065                         return false;
1066                 }
1067
1068                 if (!$found) {
1069                         dba::insert('workerqueue', array('parameter' => $parameters, 'created' => $created, 'priority' => $priority));
1070                 }
1071
1072                 // Should we quit and wait for the worker to be called as a cronjob?
1073                 if ($dont_fork) {
1074                         return true;
1075                 }
1076
1077                 // If there is a lock then we don't have to check for too much worker
1078                 if (!Lock::set('poller_worker', 0)) {
1079                         return true;
1080                 }
1081
1082                 // If there are already enough workers running, don't fork another one
1083                 $quit = self::tooMuchWorkers();
1084                 Lock::remove('poller_worker');
1085
1086                 if ($quit) {
1087                         return true;
1088                 }
1089
1090                 // Now call the worker to execute the jobs that we just added to the queue
1091                 self::spawnWorker();
1092
1093                 return true;
1094         }
1095 }