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