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