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