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