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