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