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