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