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