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