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