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