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