]> git.mxchange.org Git - friendica.git/blob - include/poller.php
0c92d00875f865248882e5d274a179e23db1645c
[friendica.git] / include / poller.php
1 <?php
2
3 use Friendica\App;
4 use Friendica\Core\Config;
5 use Friendica\Util\Lock;
6
7 if (!file_exists("boot.php") && (sizeof($_SERVER["argv"]) != 0)) {
8         $directory = dirname($_SERVER["argv"][0]);
9
10         if (substr($directory, 0, 1) != "/") {
11                 $directory = $_SERVER["PWD"]."/".$directory;
12         }
13         $directory = realpath($directory."/..");
14
15         chdir($directory);
16 }
17
18 require_once("boot.php");
19
20 function poller_run($argv, $argc){
21         global $a, $db;
22
23         $a = new App(dirname(__DIR__));
24
25         @include(".htconfig.php");
26         require_once("include/dba.php");
27         $db = new dba($db_host, $db_user, $db_pass, $db_data);
28         unset($db_host, $db_user, $db_pass, $db_data);
29
30         Config::load();
31
32         // Quit when in maintenance
33         if (Config::get('system', 'maintenance', true)) {
34                 return;
35         }
36
37         $a->set_baseurl(Config::get('system', 'url'));
38
39         load_hooks();
40
41         // At first check the maximum load. We shouldn't continue with a high load
42         if ($a->maxload_reached()) {
43                 logger('Pre check: maximum load reached, quitting.', LOGGER_DEBUG);
44                 return;
45         }
46
47         // We now start the process. This is done after the load check since this could increase the load.
48         $a->start_process();
49
50         // Kill stale processes every 5 minutes
51         $last_cleanup = Config::get('system', 'poller_last_cleaned', 0);
52         if (time() > ($last_cleanup + 300)) {
53                 Config::set('system', 'poller_last_cleaned', time());
54                 poller_kill_stale_workers();
55         }
56
57         // Count active workers and compare them with a maximum value that depends on the load
58         if (poller_too_much_workers()) {
59                 logger('Pre check: Active worker limit reached, quitting.', LOGGER_DEBUG);
60                 return;
61         }
62
63         // Do we have too few memory?
64         if ($a->min_memory_reached()) {
65                 logger('Pre check: Memory limit reached, quitting.', LOGGER_DEBUG);
66                 return;
67         }
68
69         // Possibly there are too much database connections
70         if (poller_max_connections_reached()) {
71                 logger('Pre check: maximum connections reached, quitting.', LOGGER_DEBUG);
72                 return;
73         }
74
75         // Possibly there are too much database processes that block the system
76         if ($a->max_processes_reached()) {
77                 logger('Pre check: maximum processes reached, quitting.', LOGGER_DEBUG);
78                 return;
79         }
80
81         // Now we start additional cron processes if we should do so
82         if (($argc <= 1) || ($argv[1] != "no_cron")) {
83                 poller_run_cron();
84         }
85
86         $starttime = time();
87
88         // We fetch the next queue entry that is about to be executed
89         while ($r = poller_worker_process()) {
90                 foreach ($r AS $entry) {
91                         // Assure that the priority is an integer value
92                         $entry['priority'] = (int)$entry['priority'];
93
94                         // The work will be done
95                         if (!poller_execute($entry)) {
96                                 logger('Process execution failed, quitting.', LOGGER_DEBUG);
97                                 return;
98                         }
99
100                         // To avoid the quitting of multiple pollers only one poller at a time will execute the check
101                         if (Lock::set('poller_worker', 0)) {
102                                 // Count active workers and compare them with a maximum value that depends on the load
103                                 if (poller_too_much_workers()) {
104                                         logger('Active worker limit reached, quitting.', LOGGER_DEBUG);
105                                         return;
106                                 }
107
108                                 // Check free memory
109                                 if ($a->min_memory_reached()) {
110                                         logger('Memory limit reached, quitting.', LOGGER_DEBUG);
111                                         return;
112                                 }
113                                 Lock::remove('poller_worker');
114                         }
115                 }
116
117                 // Quit the poller once every hour
118                 if (time() > ($starttime + 3600)) {
119                         logger('Process lifetime reached, quitting.', LOGGER_DEBUG);
120                         return;
121                 }
122         }
123         logger("Couldn't select a workerqueue entry, quitting.", LOGGER_DEBUG);
124 }
125
126 /**
127  * @brief Returns the number of non executed entries in the worker queue
128  *
129  * @return integer Number of non executed entries in the worker queue
130  */
131 function poller_total_entries() {
132         $s = q("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` <= '%s'", dbesc(NULL_DATE));
133         return $s[0]["total"];
134 }
135
136 /**
137  * @brief Returns the highest priority in the worker queue that isn't executed
138  *
139  * @return integer Number of active poller processes
140  */
141 function poller_highest_priority() {
142         $s = q("SELECT `priority` FROM `workerqueue` WHERE `executed` <= '%s' ORDER BY `priority` LIMIT 1", dbesc(NULL_DATE));
143         return $s[0]["priority"];
144 }
145
146 /**
147  * @brief Returns if a process with the given priority is running
148  *
149  * @param integer $priority The priority that should be checked
150  *
151  * @return integer Is there a process running with that priority?
152  */
153 function poller_process_with_priority_active($priority) {
154         $s = q("SELECT `id` FROM `workerqueue` WHERE `priority` <= %d AND `executed` > '%s' LIMIT 1",
155                         intval($priority), dbesc(NULL_DATE));
156         return dbm::is_result($s);
157 }
158
159 /**
160  * @brief Execute a worker entry
161  *
162  * @param array $queue Workerqueue entry
163  *
164  * @return boolean "true" if further processing should be stopped
165  */
166 function poller_execute($queue) {
167
168         $a = get_app();
169
170         $mypid = getmypid();
171
172         // Quit when in maintenance
173         if (Config::get('system', 'maintenance', true)) {
174                 logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
175                 return false;
176         }
177
178         // Constantly check the number of parallel database processes
179         if ($a->max_processes_reached()) {
180                 logger("Max processes reached for process ".$mypid, LOGGER_DEBUG);
181                 return false;
182         }
183
184         // Constantly check the number of available database connections to let the frontend be accessible at any time
185         if (poller_max_connections_reached()) {
186                 logger("Max connection reached for process ".$mypid, LOGGER_DEBUG);
187                 return false;
188         }
189
190         $argv = json_decode($queue["parameter"]);
191
192         // Check for existance and validity of the include file
193         $include = $argv[0];
194
195         if (!validate_include($include)) {
196                 logger("Include file ".$argv[0]." is not valid!");
197                 dba::delete('workerqueue', array('id' => $queue["id"]));
198                 return true;
199         }
200
201         require_once($include);
202
203         $funcname = str_replace(".php", "", basename($argv[0]))."_run";
204
205         if (function_exists($funcname)) {
206                 poller_exec_function($queue, $funcname, $argv);
207                 dba::delete('workerqueue', array('id' => $queue["id"]));
208         } else {
209                 logger("Function ".$funcname." does not exist");
210         }
211
212         return true;
213 }
214
215 /**
216  * @brief Execute a function from the queue
217  *
218  * @param array $queue Workerqueue entry
219  * @param string $funcname name of the function
220  * @param array $argv Array of values to be passed to the function
221  */
222 function poller_exec_function($queue, $funcname, $argv) {
223
224         $a = get_app();
225
226         $mypid = getmypid();
227
228         $argc = count($argv);
229
230         logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]);
231
232         $stamp = (float)microtime(true);
233
234         // We use the callstack here to analyze the performance of executed worker entries.
235         // For this reason the variables have to be initialized.
236         if (Config::get("system", "profiler")) {
237                 $a->performance["start"] = microtime(true);
238                 $a->performance["database"] = 0;
239                 $a->performance["database_write"] = 0;
240                 $a->performance["network"] = 0;
241                 $a->performance["file"] = 0;
242                 $a->performance["rendering"] = 0;
243                 $a->performance["parser"] = 0;
244                 $a->performance["marktime"] = 0;
245                 $a->performance["markstart"] = microtime(true);
246                 $a->callstack = array();
247         }
248
249         // For better logging create a new process id for every worker call
250         // But preserve the old one for the worker
251         $old_process_id = $a->process_id;
252         $a->process_id = uniqid("wrk", true);
253         $a->queue = $queue;
254
255         $funcname($argv, $argc);
256
257         $a->process_id = $old_process_id;
258         unset($a->queue);
259
260         $duration = number_format(microtime(true) - $stamp, 3);
261
262         if ($duration > 3600) {
263                 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 1 hour (".round($duration/60, 3).")", LOGGER_DEBUG);
264         } elseif ($duration > 600) {
265                 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 10 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
266         } elseif ($duration > 300) {
267                 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 5 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
268         } elseif ($duration > 120) {
269                 logger("Prio ".$queue["priority"].": ".$queue["parameter"]." - longer than 2 minutes (".round($duration/60, 3).")", LOGGER_DEBUG);
270         }
271
272         logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - done in ".$duration." seconds.");
273
274         // Write down the performance values into the log
275         if (Config::get("system", "profiler")) {
276                 $duration = microtime(true)-$a->performance["start"];
277
278                 if (Config::get("rendertime", "callstack")) {
279                         if (isset($a->callstack["database"])) {
280                                 $o = "\nDatabase Read:\n";
281                                 foreach ($a->callstack["database"] AS $func => $time) {
282                                         $time = round($time, 3);
283                                         if ($time > 0) {
284                                                 $o .= $func.": ".$time."\n";
285                                         }
286                                 }
287                         }
288                         if (isset($a->callstack["database_write"])) {
289                                 $o .= "\nDatabase Write:\n";
290                                 foreach ($a->callstack["database_write"] AS $func => $time) {
291                                         $time = round($time, 3);
292                                         if ($time > 0) {
293                                                 $o .= $func.": ".$time."\n";
294                                         }
295                                 }
296                         }
297                         if (isset($a->callstack["network"])) {
298                                 $o .= "\nNetwork:\n";
299                                 foreach ($a->callstack["network"] AS $func => $time) {
300                                         $time = round($time, 3);
301                                         if ($time > 0) {
302                                                 $o .= $func.": ".$time."\n";
303                                         }
304                                 }
305                         }
306                 } else {
307                         $o = '';
308                 }
309
310                 logger("ID ".$queue["id"].": ".$funcname.": ".sprintf("DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
311                         number_format($a->performance["database"] - $a->performance["database_write"], 2),
312                         number_format($a->performance["database_write"], 2),
313                         number_format($a->performance["network"], 2),
314                         number_format($a->performance["file"], 2),
315                         number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
316                         number_format($duration, 2)),
317                         LOGGER_DEBUG);
318         }
319
320         $cooldown = Config::get("system", "worker_cooldown", 0);
321
322         if ($cooldown > 0) {
323                 logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." - in cooldown for ".$cooldown." seconds");
324                 sleep($cooldown);
325         }
326 }
327
328 /**
329  * @brief Checks if the number of database connections has reached a critical limit.
330  *
331  * @return bool Are more than 3/4 of the maximum connections used?
332  */
333 function poller_max_connections_reached() {
334
335         // Fetch the max value from the config. This is needed when the system cannot detect the correct value by itself.
336         $max = Config::get("system", "max_connections");
337
338         // Fetch the percentage level where the poller will get active
339         $maxlevel = Config::get("system", "max_connections_level", 75);
340
341         if ($max == 0) {
342                 // the maximum number of possible user connections can be a system variable
343                 $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_user_connections'");
344                 if (dbm::is_result($r)) {
345                         $max = $r[0]["Value"];
346                 }
347                 // Or it can be granted. This overrides the system variable
348                 $r = q("SHOW GRANTS");
349                 if (dbm::is_result($r)) {
350                         foreach ($r AS $grants) {
351                                 $grant = array_pop($grants);
352                                 if (stristr($grant, "GRANT USAGE ON")) {
353                                         if (preg_match("/WITH MAX_USER_CONNECTIONS (\d*)/", $grant, $match)) {
354                                                 $max = $match[1];
355                                         }
356                                 }
357                         }
358                 }
359         }
360
361         // If $max is set we will use the processlist to determine the current number of connections
362         // The processlist only shows entries of the current user
363         if ($max != 0) {
364                 $r = q("SHOW PROCESSLIST");
365                 if (!dbm::is_result($r)) {
366                         return false;
367                 }
368                 $used = count($r);
369
370                 logger("Connection usage (user values): ".$used."/".$max, LOGGER_DEBUG);
371
372                 $level = ($used / $max) * 100;
373
374                 if ($level >= $maxlevel) {
375                         logger("Maximum level (".$maxlevel."%) of user connections reached: ".$used."/".$max);
376                         return true;
377                 }
378         }
379
380         // We will now check for the system values.
381         // This limit could be reached although the user limits are fine.
382         $r = q("SHOW VARIABLES WHERE `variable_name` = 'max_connections'");
383         if (!dbm::is_result($r)) {
384                 return false;
385         }
386         $max = intval($r[0]["Value"]);
387         if ($max == 0) {
388                 return false;
389         }
390         $r = q("SHOW STATUS WHERE `variable_name` = 'Threads_connected'");
391         if (!dbm::is_result($r)) {
392                 return false;
393         }
394         $used = intval($r[0]["Value"]);
395         if ($used == 0) {
396                 return false;
397         }
398         logger("Connection usage (system values): ".$used."/".$max, LOGGER_DEBUG);
399
400         $level = $used / $max * 100;
401
402         if ($level < $maxlevel) {
403                 return false;
404         }
405         logger("Maximum level (".$level."%) of system connections reached: ".$used."/".$max);
406         return true;
407 }
408
409 /**
410  * @brief fix the queue entry if the worker process died
411  *
412  */
413 function poller_kill_stale_workers() {
414         $r = q("SELECT `pid`, `executed`, `priority`, `parameter` FROM `workerqueue` WHERE `executed` > '%s'", dbesc(NULL_DATE));
415
416         if (!dbm::is_result($r)) {
417                 // No processing here needed
418                 return;
419         }
420
421         foreach ($r AS $pid) {
422                 if (!posix_kill($pid["pid"], 0)) {
423                         dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0),
424                                         array('pid' => $pid["pid"]));
425                 } else {
426                         // Kill long running processes
427
428                         // Check if the priority is in a valid range
429                         if (!in_array($pid["priority"], array(PRIORITY_CRITICAL, PRIORITY_HIGH, PRIORITY_MEDIUM, PRIORITY_LOW, PRIORITY_NEGLIGIBLE))) {
430                                 $pid["priority"] = PRIORITY_MEDIUM;
431                         }
432
433                         // Define the maximum durations
434                         $max_duration_defaults = array(PRIORITY_CRITICAL => 360, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 360);
435                         $max_duration = $max_duration_defaults[$pid["priority"]];
436
437                         $argv = json_decode($pid["parameter"]);
438                         $argv[0] = basename($argv[0]);
439
440                         // How long is the process already running?
441                         $duration = (time() - strtotime($pid["executed"])) / 60;
442                         if ($duration > $max_duration) {
443                                 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") took more than ".$max_duration." minutes. It will be killed now.");
444                                 posix_kill($pid["pid"], SIGTERM);
445
446                                 // We killed the stale process.
447                                 // To avoid a blocking situation we reschedule the process at the beginning of the queue.
448                                 // Additionally we are lowering the priority.
449                                 dba::update('workerqueue',
450                                                 array('executed' => NULL_DATE, 'created' => datetime_convert(), 'priority' => PRIORITY_NEGLIGIBLE, 'pid' => 0),
451                                                 array('pid' => $pid["pid"]));
452                         } else {
453                                 logger("Worker process ".$pid["pid"]." (".implode(" ", $argv).") now runs for ".round($duration)." of ".$max_duration." allowed minutes. That's okay.", LOGGER_DEBUG);
454                         }
455                 }
456         }
457 }
458
459 /**
460  * @brief Checks if the number of active workers exceeds the given limits
461  *
462  * @param integer $entries The number of not executed entries in the worker queue
463  * @param integer $top_priority The highest not executed priority in the worker queue
464  * @param boolean $high_running Is a process with priority "$top_priority" running?
465  *
466  * @return bool Are there too much workers running?
467  */
468 function poller_too_much_workers() {
469         $queues = Config::get("system", "worker_queues", 4);
470
471         $maxqueues = $queues;
472
473         $active = poller_active_workers();
474
475         // Decrease the number of workers at higher load
476         $load = current_load();
477         if ($load) {
478                 $maxsysload = intval(Config::get("system", "maxloadavg", 50));
479
480                 $maxworkers = $queues;
481
482                 // Some magical mathemathics to reduce the workers
483                 $exponent = 3;
484                 $slope = $maxworkers / pow($maxsysload, $exponent);
485                 $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
486
487                 if (Config::get('system', 'worker_debug')) {
488                         // Create a list of queue entries grouped by their priority
489                         $listitem = array();
490
491                         // Adding all processes with no workerqueue entry
492                         $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` WHERE NOT EXISTS (SELECT id FROM `workerqueue` WHERE `workerqueue`.`pid` = `process`.`pid`)");
493                         if ($process = dba::fetch($processes)) {
494                                 $listitem[0] = "0:".$process["running"];
495                         }
496                         dba::close($processes);
497
498                         // Now adding all processes with workerqueue entries
499                         $entries = dba::p("SELECT COUNT(*) AS `entries`, `priority` FROM `workerqueue` GROUP BY `priority`");
500                         while ($entry = dba::fetch($entries)) {
501                                 $processes = dba::p("SELECT COUNT(*) AS `running` FROM `process` INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid` WHERE `priority` = ?", $entry["priority"]);
502                                 if ($process = dba::fetch($processes)) {
503                                         $listitem[$entry["priority"]] = $entry["priority"].":".$process["running"]."/".$entry["entries"];
504                                 }
505                                 dba::close($processes);
506                         }
507                         dba::close($entries);
508                         $processlist = ' ('.implode(', ', $listitem).')';
509                 }
510
511                 $entries = poller_total_entries();
512
513                 if (Config::get("system", "worker_fastlane", false) && ($queues > 0) && ($entries > 0) && ($active >= $queues)) {
514                         $top_priority = poller_highest_priority();
515                         $high_running = poller_process_with_priority_active($top_priority);
516
517                         if (!$high_running && ($top_priority > PRIORITY_UNDEFINED) && ($top_priority < PRIORITY_NEGLIGIBLE)) {
518                                 logger("There are jobs with priority ".$top_priority." waiting but none is executed. Open a fastlane.", LOGGER_DEBUG);
519                                 $queues = $active + 1;
520                         }
521                 }
522
523                 logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
524
525                 // Are there fewer workers running as possible? Then fork a new one.
526                 if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
527                         logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
528                         $args = array("include/poller.php", "no_cron");
529                         $a = get_app();
530                         $a->proc_run($args);
531                 }
532         }
533
534         return $active >= $queues;
535 }
536
537 /**
538  * @brief Returns the number of active poller processes
539  *
540  * @return integer Number of active poller processes
541  */
542 function poller_active_workers() {
543         $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'poller.php'");
544
545         return $workers[0]["processes"];
546 }
547
548 /**
549  * @brief Check if we should pass some slow processes
550  *
551  * When the active processes of the highest priority are using more than 2/3
552  * of all processes, we let pass slower processes.
553  *
554  * @param string $highest_priority Returns the currently highest priority
555  * @return bool We let pass a slower process than $highest_priority
556  */
557 function poller_passing_slow(&$highest_priority) {
558
559         $highest_priority = 0;
560
561         $r = q("SELECT `priority`
562                 FROM `process`
563                 INNER JOIN `workerqueue` ON `workerqueue`.`pid` = `process`.`pid`");
564
565         // No active processes at all? Fine
566         if (!dbm::is_result($r)) {
567                 return false;
568         }
569         $priorities = array();
570         foreach ($r AS $line) {
571                 $priorities[] = $line["priority"];
572         }
573         // Should not happen
574         if (count($priorities) == 0) {
575                 return false;
576         }
577         $highest_priority = min($priorities);
578
579         // The highest process is already the slowest one?
580         // Then we quit
581         if ($highest_priority == PRIORITY_NEGLIGIBLE) {
582                 return false;
583         }
584         $high = 0;
585         foreach ($priorities AS $priority) {
586                 if ($priority == $highest_priority) {
587                         ++$high;
588                 }
589         }
590         logger("Highest priority: ".$highest_priority." Total processes: ".count($priorities)." Count high priority processes: ".$high, LOGGER_DEBUG);
591         $passing_slow = (($high/count($priorities)) > (2/3));
592
593         if ($passing_slow) {
594                 logger("Passing slower processes than priority ".$highest_priority, LOGGER_DEBUG);
595         }
596         return $passing_slow;
597 }
598
599 /**
600  * @brief Find and claim the next worker process for us
601  *
602  * @return boolean Have we found something?
603  */
604 function find_worker_processes() {
605         // Check if we should pass some low priority process
606         $highest_priority = 0;
607         $found = false;
608
609         if (poller_passing_slow($highest_priority)) {
610                 // Are there waiting processes with a higher priority than the currently highest?
611                 $result = dba::p("UPDATE `workerqueue` SET `executed` = ?, `pid` = ?
612                                         WHERE `executed` <= ? AND `priority` < ?
613                                         ORDER BY `priority`, `created` LIMIT 1",
614                                 datetime_convert(), getmypid(), NULL_DATE, $highest_priority);
615                 if (dbm::is_result($result)) {
616                         $found = (dba::num_rows($result) > 0);
617                 }
618                 dba::close($result);
619
620                 if (!$found) {
621                         // Give slower processes some processing time
622                         $result = dba::p("UPDATE `workerqueue` SET `executed` = ?, `pid` = ?
623                                                 WHERE `executed` <= ? AND `priority` > ?
624                                                 ORDER BY `priority`, `created` LIMIT 1",
625                                         datetime_convert(), getmypid(), NULL_DATE, $highest_priority);
626                         if (dbm::is_result($result)) {
627                                 $found = (dba::num_rows($result) > 0);
628                         }
629                         dba::close($result);
630                 }
631         }
632
633         // If there is no result (or we shouldn't pass lower processes) we check without priority limit
634         if (!$found) {
635                 $result = dba::p("UPDATE `workerqueue` SET `executed` = ?, `pid` = ? WHERE `executed` <= ? ORDER BY `priority`, `created` LIMIT 1",
636                                 datetime_convert(), getmypid(), NULL_DATE);
637                 if (dbm::is_result($result)) {
638                         $found = (dba::num_rows($result) > 0);
639                 }
640                 dba::close($result);
641         }
642         return $found;
643 }
644
645 /**
646  * @brief Returns the next worker process
647  *
648  * @return string SQL statement
649  */
650 function poller_worker_process() {
651
652         $stamp = (float)microtime(true);
653
654         $timeout = 10;
655         do {
656                 $found = find_worker_processes();
657         } while (!$found && (poller_total_entries() > 0) && (--$timeout > 0));
658
659         logger('Duration: '.number_format(microtime(true) - $stamp, 3), LOGGER_DEBUG);
660
661         if ($found) {
662                 $r = q("SELECT * FROM `workerqueue` WHERE `pid` = %d", intval(getmypid()));
663         }
664         return $r;
665 }
666
667 /**
668  * @brief Removes a workerqueue entry from the current process
669  */
670 function poller_unclaim_process() {
671         $mypid = getmypid();
672
673         dba::update('workerqueue', array('executed' => NULL_DATE, 'pid' => 0), array('pid' => $mypid));
674 }
675
676 /**
677  * @brief Call the front end worker
678  */
679 function call_worker() {
680         if (!Config::get("system", "frontend_worker")) {
681                 return;
682         }
683
684         $url = App::get_baseurl()."/worker";
685         fetch_url($url, false, $redirects, 1);
686 }
687
688 /**
689  * @brief Call the front end worker if there aren't any active
690  */
691 function call_worker_if_idle() {
692         if (!Config::get("system", "frontend_worker")) {
693                 return;
694         }
695
696         // Do we have "proc_open"? Then we can fork the poller
697         if (function_exists("proc_open")) {
698                 // When was the last time that we called the worker?
699                 // Less than one minute? Then we quit
700                 if ((time() - Config::get("system", "worker_started")) < 60) {
701                         return;
702                 }
703
704                 set_config("system", "worker_started", time());
705
706                 // Do we have enough running workers? Then we quit here.
707                 if (poller_too_much_workers()) {
708                         // Cleaning dead processes
709                         poller_kill_stale_workers();
710                         get_app()->remove_inactive_processes();
711
712                         return;
713                 }
714
715                 poller_run_cron();
716
717                 logger('Call poller', LOGGER_DEBUG);
718
719                 $args = array("include/poller.php", "no_cron");
720                 $a = get_app();
721                 $a->proc_run($args);
722                 return;
723         }
724
725         // We cannot execute background processes.
726         // We now run the processes from the frontend.
727         // This won't work with long running processes.
728         poller_run_cron();
729
730         clear_worker_processes();
731
732         $workers = q("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
733
734         if ($workers[0]["processes"] == 0) {
735                 call_worker();
736         }
737 }
738
739 /**
740  * @brief Removes long running worker processes
741  */
742 function clear_worker_processes() {
743         $timeout = Config::get("system", "frontend_worker_timeout", 10);
744
745         /// @todo We should clean up the corresponding workerqueue entries as well
746         q("DELETE FROM `process` WHERE `created` < '%s' AND `command` = 'worker.php'",
747                 dbesc(datetime_convert('UTC','UTC',"now - ".$timeout." minutes")));
748 }
749
750 /**
751  * @brief Runs the cron processes
752  */
753 function poller_run_cron() {
754         logger('Add cron entries', LOGGER_DEBUG);
755
756         // Check for spooled items
757         proc_run(PRIORITY_HIGH, "include/spool_post.php");
758
759         // Run the cron job that calls all other jobs
760         proc_run(PRIORITY_MEDIUM, "include/cron.php");
761
762         // Run the cronhooks job separately from cron for being able to use a different timing
763         proc_run(PRIORITY_MEDIUM, "include/cronhooks.php");
764
765         // Cleaning dead processes
766         poller_kill_stale_workers();
767 }
768
769 if (array_search(__file__,get_included_files())===0){
770         poller_run($_SERVER["argv"],$_SERVER["argc"]);
771
772         poller_unclaim_process();
773
774         get_app()->end_process();
775
776         Lock::remove('poller_worker');
777
778         killme();
779 }