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