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