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