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