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