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