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