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