*/
namespace Friendica\Core;
-use Friendica\Core\Addon;
-use Friendica\Core\Config;
-use Friendica\Core\System;
+use dba;
use Friendica\Database\DBM;
use Friendica\Model\Process;
use Friendica\Util\DateTimeFormat;
-use Friendica\Util\Lock;
use Friendica\Util\Network;
-use dba;
require_once 'include/dba.php';
self::startProcess();
// Kill stale processes every 5 minutes
- $last_cleanup = Config::get('system', 'poller_last_cleaned', 0);
+ $last_cleanup = Config::get('system', 'worker_last_cleaned', 0);
if (time() > ($last_cleanup + 300)) {
- Config::set('system', 'poller_last_cleaned', time());
+ Config::set('system', 'worker_last_cleaned', time());
self::killStaleWorkers();
}
}
// If possible we will fetch new jobs for this worker
- if (!$refetched && Lock::set('poller_worker_process', 0)) {
+ if (!$refetched && Lock::acquire('worker_process', 0)) {
$stamp = (float)microtime(true);
$refetched = self::findWorkerProcesses($passing_slow);
self::$db_duration += (microtime(true) - $stamp);
- Lock::remove('poller_worker_process');
+ Lock::release('worker_process');
}
}
// To avoid the quitting of multiple workers only one worker at a time will execute the check
- if (Lock::set('poller_worker', 0)) {
+ if (Lock::acquire('worker', 0)) {
$stamp = (float)microtime(true);
// Count active workers and compare them with a maximum value that depends on the load
if (self::tooMuchWorkers()) {
logger('Memory limit reached, quitting.', LOGGER_DEBUG);
return;
}
- Lock::remove('poller_worker');
+ Lock::release('worker');
self::$db_duration += (microtime(true) - $stamp);
}
return;
}
}
- logger("Couldn't select a workerqueue entry, quitting.", LOGGER_DEBUG);
+
+ // Cleaning up. Possibly not needed, but it doesn't harm anything.
+ if (Config::get('system', 'worker_daemon_mode', false)) {
+ self::IPCSetJobState(false);
+ }
+ logger("Couldn't select a workerqueue entry, quitting process " . getmypid() . ".", LOGGER_DEBUG);
}
/**
*/
private static function totalEntries()
{
- $s = dba::fetch_first("SELECT COUNT(*) AS `total` FROM `workerqueue` WHERE `executed` <= ? AND NOT `done`", NULL_DATE);
- if (DBM::is_result($s)) {
- return $s["total"];
- } else {
- return 0;
- }
+ return dba::count('workerqueue', ["`executed` <= ? AND NOT `done`", NULL_DATE]);
}
/**
$mypid = getmypid();
// Quit when in maintenance
- if (Config::get('system', 'maintenance', true)) {
+ if (Config::get('system', 'maintenance', false, true)) {
logger("Maintenance mode - quit process ".$mypid, LOGGER_DEBUG);
return false;
}
return false;
}
- $argv = json_decode($queue["parameter"]);
+ $argv = json_decode($queue["parameter"], true);
// Check for existance and validity of the include file
$include = $argv[0];
$stamp = (float)microtime(true);
if (dba::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
- Config::set('system', 'last_poller_execution', DateTimeFormat::utcNow());
+ Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
}
self::$db_duration = (microtime(true) - $stamp);
$stamp = (float)microtime(true);
if (dba::update('workerqueue', ['done' => true], ['id' => $queue["id"]])) {
- Config::set('system', 'last_poller_execution', DateTimeFormat::utcNow());
+ Config::set('system', 'last_worker_execution', DateTimeFormat::utcNow());
}
self::$db_duration = (microtime(true) - $stamp);
} else {
$argc = count($argv);
- $new_process_id = uniqid("wrk", true);
+ $new_process_id = System::processID("wrk");
logger("Process ".$mypid." - Prio ".$queue["priority"]." - ID ".$queue["id"].": ".$funcname." ".$queue["parameter"]." - Process PID: ".$new_process_id);
$a->performance["start"] = microtime(true);
$a->performance["database"] = 0;
$a->performance["database_write"] = 0;
+ $a->performance["cache"] = 0;
+ $a->performance["cache_write"] = 0;
$a->performance["network"] = 0;
$a->performance["file"] = 0;
$a->performance["rendering"] = 0;
if (Config::get("system", "profiler")) {
$duration = microtime(true)-$a->performance["start"];
+ $o = '';
if (Config::get("rendertime", "callstack")) {
if (isset($a->callstack["database"])) {
- $o = "\nDatabase Read:\n";
+ $o .= "\nDatabase Read:\n";
foreach ($a->callstack["database"] as $func => $time) {
$time = round($time, 3);
if ($time > 0) {
}
}
}
+ if (isset($a->callstack["dache"])) {
+ $o .= "\nCache Read:\n";
+ foreach ($a->callstack["dache"] as $func => $time) {
+ $time = round($time, 3);
+ if ($time > 0) {
+ $o .= $func.": ".$time."\n";
+ }
+ }
+ }
+ if (isset($a->callstack["dache_write"])) {
+ $o .= "\nCache Write:\n";
+ foreach ($a->callstack["dache_write"] as $func => $time) {
+ $time = round($time, 3);
+ if ($time > 0) {
+ $o .= $func.": ".$time."\n";
+ }
+ }
+ }
if (isset($a->callstack["network"])) {
$o .= "\nNetwork:\n";
foreach ($a->callstack["network"] as $func => $time) {
}
}
}
- } else {
- $o = '';
}
logger(
"ID ".$queue["id"].": ".$funcname.": ".sprintf(
- "DB: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
+ "DB: %s/%s, Cache: %s/%s, Net: %s, I/O: %s, Other: %s, Total: %s".$o,
number_format($a->performance["database"] - $a->performance["database_write"], 2),
number_format($a->performance["database_write"], 2),
+ number_format($a->performance["cache"], 2),
+ number_format($a->performance["cache_write"], 2),
number_format($a->performance["network"], 2),
number_format($a->performance["file"], 2),
- number_format($duration - ($a->performance["database"] + $a->performance["network"] + $a->performance["file"]), 2),
+ number_format($duration - ($a->performance["database"]
+ + $a->performance["cache"] + $a->performance["cache_write"]
+ + $a->performance["network"] + $a->performance["file"]), 2),
number_format($duration, 2)
),
LOGGER_DEBUG
$max_duration_defaults = [PRIORITY_CRITICAL => 720, PRIORITY_HIGH => 10, PRIORITY_MEDIUM => 60, PRIORITY_LOW => 180, PRIORITY_NEGLIGIBLE => 720];
$max_duration = $max_duration_defaults[$entry["priority"]];
- $argv = json_decode($entry["parameter"]);
+ $argv = json_decode($entry["parameter"], true);
$argv[0] = basename($argv[0]);
// How long is the process already running?
// We killed the stale process.
// To avoid a blocking situation we reschedule the process at the beginning of the queue.
// Additionally we are lowering the priority. (But not PRIORITY_CRITICAL)
+ $new_priority = $entry["priority"];
if ($entry["priority"] == PRIORITY_HIGH) {
$new_priority = PRIORITY_MEDIUM;
} elseif ($entry["priority"] == PRIORITY_MEDIUM) {
if ($load) {
$maxsysload = intval(Config::get("system", "maxloadavg", 50));
- $maxworkers = $queues;
+ /* Default exponent 3 causes queues to rapidly decrease as load increases.
+ * If you have 20 max queues at idle, then you get only 5 queues at 37.1% of $maxsysload.
+ * For some environments, this rapid decrease is not needed.
+ * With exponent 1, you could have 20 max queues at idle and 13 at 37% of $maxsysload.
+ */
+ $exponent = intval(Config::get('system', 'worker_load_exponent', 3));
+ $slope = pow(max(0, $maxsysload - $load) / $maxsysload, $exponent);
+ $queues = intval(ceil($slope * $maxqueues));
- // Some magical mathemathics to reduce the workers
- $exponent = 3;
- $slope = $maxworkers / pow($maxsysload, $exponent);
- $queues = ceil($slope * pow(max(0, $maxsysload - $load), $exponent));
$processlist = '';
if (Config::get('system', 'worker_debug')) {
logger("Load: ".$load."/".$maxsysload." - processes: ".$active."/".$entries.$processlist." - maximum: ".$queues."/".$maxqueues, LOGGER_DEBUG);
// Are there fewer workers running as possible? Then fork a new one.
- if (!Config::get("system", "worker_dont_fork") && ($queues > ($active + 1)) && ($entries > 1)) {
+ if (!Config::get("system", "worker_dont_fork", false) && ($queues > ($active + 1)) && ($entries > 1)) {
logger("Active workers: ".$active."/".$queues." Fork a new worker.", LOGGER_DEBUG);
- self::spawnWorker();
+ if (Config::get('system', 'worker_daemon_mode', false)) {
+ self::IPCSetJobState(true);
+ } else {
+ self::spawnWorker();
+ }
}
}
- return $active >= $queues;
+ // if there are too much worker, we don't spawn a new one.
+ if (Config::get('system', 'worker_daemon_mode', false) && ($active > $queues)) {
+ self::IPCSetJobState(false);
+ }
+
+ return $active > $queues;
}
/**
*/
private static function activeWorkers()
{
- $workers = dba::fetch_first("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'Worker.php'");
-
- return $workers["processes"];
+ return dba::count('process', ['command' => 'Worker.php']);
}
/**
$limit = min($queue_length, ceil($slope * pow($jobs, $exponent)));
logger('Total: '.$jobs.' - Maximum: '.$queue_length.' - jobs per queue: '.$limit, LOGGER_DEBUG);
-
+ $ids = [];
if (self::passingSlow($highest_priority)) {
// Are there waiting processes with a higher priority than the currently highest?
$result = dba::select(
dba::close($r);
$stamp = (float)microtime(true);
- if (!Lock::set('poller_worker_process')) {
+ if (!Lock::acquire('worker_process')) {
return false;
}
self::$lock_duration = (microtime(true) - $stamp);
$found = self::findWorkerProcesses($passing_slow);
self::$db_duration += (microtime(true) - $stamp);
- Lock::remove('poller_worker_process');
+ Lock::release('worker_process');
if ($found) {
$r = dba::select('workerqueue', [], ['pid' => getmypid(), 'done' => false]);
self::clearProcesses();
- $workers = dba::fetch_first("SELECT COUNT(*) AS `processes` FROM `process` WHERE `command` = 'worker.php'");
+ $workers = self::activeWorkers();
- if ($workers["processes"] == 0) {
+ if ($workers == 0) {
self::callWorker();
}
}
}
/**
+ * @brief Spawns a new worker
* @return void
*/
- public static function spawnWorker()
+ public static function spawnWorker($do_cron = false)
{
- $args = ["scripts/worker.php", "no_cron"];
+ $args = ["bin/worker.php"];
+
+ if (!$do_cron) {
+ $args[] = "no_cron";
+ }
+
get_app()->proc_run($args);
+
+ // after spawning we have to remove the flag.
+ if (Config::get('system', 'worker_daemon_mode', false)) {
+ self::IPCSetJobState(false);
+ }
}
/**
*/
public static function add($cmd)
{
- $proc_args = func_get_args();
+ $args = func_get_args();
- $args = [];
- if (!count($proc_args)) {
+ if (!count($args)) {
return false;
}
- // Preserve the first parameter
- // It could contain a command, the priority or an parameter array
- // If we use the parameter array we have to protect it from the following function
- $run_parameter = array_shift($proc_args);
-
- // expand any arrays
- foreach ($proc_args as $arg) {
- if (is_array($arg)) {
- foreach ($arg as $n) {
- $args[] = $n;
- }
- } else {
- $args[] = $arg;
- }
- }
-
- // Now we add the run parameters back to the array
- array_unshift($args, $run_parameter);
-
$arr = ['args' => $args, 'run_cmd' => true];
Addon::callHooks("proc_run", $arr);
}
$priority = PRIORITY_MEDIUM;
- $dont_fork = Config::get("system", "worker_dont_fork");
+ $dont_fork = Config::get("system", "worker_dont_fork", false);
$created = DateTimeFormat::utcNow();
+ $run_parameter = array_shift($args);
+
if (is_int($run_parameter)) {
$priority = $run_parameter;
} elseif (is_array($run_parameter)) {
}
}
- $argv = $args;
- array_shift($argv);
-
- $parameters = json_encode($argv);
+ $parameters = json_encode($args);
$found = dba::exists('workerqueue', ['parameter' => $parameters, 'done' => false]);
// Quit if there was a database error - a precaution for the update process to 3.5.3
}
// If there is a lock then we don't have to check for too much worker
- if (!Lock::set('poller_worker', 0)) {
+ if (!Lock::acquire('worker', 0)) {
return true;
}
// If there are already enough workers running, don't fork another one
$quit = self::tooMuchWorkers();
- Lock::remove('poller_worker');
+ Lock::release('worker');
if ($quit) {
return true;
}
+ // We tell the daemon that a new job entry exists
+ if (Config::get('system', 'worker_daemon_mode', false)) {
+ // We don't have to set the IPC flag - this is done in "tooMuchWorkers"
+ return true;
+ }
+
// Now call the worker to execute the jobs that we just added to the queue
self::spawnWorker();
{
return Process::deleteByPid();
}
+
+ /**
+ * Set the flag if some job is waiting
+ *
+ * @brief Set the flag if some job is waiting
+ * @param boolean $jobs Is there a waiting job?
+ */
+ public static function IPCSetJobState($jobs)
+ {
+ dba::update('worker-ipc', ['jobs' => $jobs], ['key' => 1], true);
+ }
+
+ /**
+ * Checks if some worker job waits to be executed
+ *
+ * @brief Checks if some worker job waits to be executed
+ * @return bool
+ */
+ public static function IPCJobsExists()
+ {
+ $row = dba::selectFirst('worker-ipc', ['jobs'], ['key' => 1]);
+
+ // When we don't have a row, no job is running
+ if (!DBM::is_result($row)) {
+ return false;
+ }
+
+ return (bool)$row['jobs'];
+ }
}