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