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