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