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