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