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