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