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