4 * @copyright Copyright (C) 2020, Friendica
6 * @license GNU AGPL version 3 or any later version
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU Affero General Public License as
10 * published by the Free Software Foundation, either version 3 of the
11 * License, or (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU Affero General Public License for more details.
18 * You should have received a copy of the GNU Affero General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 * Run the worker from a daemon.
23 * This script was taken from http://php.net/manual/en/function.pcntl-fork.php
26 if (php_sapi_name() !== 'cli') {
27 header($_SERVER["SERVER_PROTOCOL"] . ' 403 Forbidden');
32 use Friendica\App\Mode;
33 use Friendica\Core\Logger;
34 use Friendica\Core\Worker;
35 use Friendica\Database\DBA;
37 use Friendica\Util\DateTimeFormat;
38 use Psr\Log\LoggerInterface;
42 $longopts = ['foreground'];
43 $options = getopt($shortopts, $longopts);
45 // Ensure that daemon.php is executed from the base path of the installation
46 if (!file_exists("boot.php") && (sizeof($_SERVER["argv"]) != 0)) {
47 $directory = dirname($_SERVER["argv"][0]);
49 if (substr($directory, 0, 1) != "/") {
50 $directory = $_SERVER["PWD"] . "/" . $directory;
52 $directory = realpath($directory . "/..");
57 require dirname(__DIR__) . '/vendor/autoload.php';
59 $dice = (new Dice())->addRules(include __DIR__ . '/../static/dependencies.config.php');
60 $dice = $dice->addRule(LoggerInterface::class,['constructParams' => ['daemon']]);
65 if (DI::mode()->isInstall()) {
66 die("Friendica isn't properly installed yet.\n");
69 DI::mode()->setExecutor(Mode::DAEMON);
73 if (empty(DI::config()->get('system', 'pidfile'))) {
75 Please set system.pidfile in config/local.config.php. For example:
78 'pidfile' => '/path/to/daemon.pid',
84 $pidfile = DI::config()->get('system', 'pidfile');
86 if (in_array("start", $_SERVER["argv"])) {
90 if (in_array("stop", $_SERVER["argv"])) {
94 if (in_array("status", $_SERVER["argv"])) {
98 $foreground = array_key_exists('f', $options) || array_key_exists('foreground', $options);
101 die("Please use either 'start', 'stop' or 'status'.\n");
104 if (empty($_SERVER["argv"][0])) {
105 die("Unexpected script behaviour. This message should never occur.\n");
110 if (is_readable($pidfile)) {
111 $pid = intval(file_get_contents($pidfile));
114 if (empty($pid) && in_array($mode, ["stop", "status"])) {
115 DI::config()->set('system', 'worker_daemon_mode', false);
116 die("Pidfile wasn't found. Is the daemon running?\n");
119 if ($mode == "status") {
120 if (posix_kill($pid, 0)) {
121 die("Daemon process $pid is running.\n");
126 DI::config()->set('system', 'worker_daemon_mode', false);
127 die("Daemon process $pid isn't running.\n");
130 if ($mode == "stop") {
131 posix_kill($pid, SIGTERM);
135 Logger::notice("Worker daemon process was killed", ["pid" => $pid]);
137 DI::config()->set('system', 'worker_daemon_mode', false);
138 die("Worker daemon process $pid was killed.\n");
141 if (!empty($pid) && posix_kill($pid, 0)) {
142 die("Daemon process $pid is already running.\n");
145 Logger::notice('Starting worker daemon.', ["pid" => $pid]);
148 echo "Starting worker daemon.\n";
152 // Fork a daemon process
155 echo "Daemon couldn't be forked.\n";
156 Logger::warning('Could not fork daemon');
159 // The parent process continues here
160 echo 'Child process started with pid ' . $pid . ".\n";
161 Logger::notice('Child process started', ['pid' => $pid]);
162 file_put_contents($pidfile, $pid);
166 // We now are in the child process
167 register_shutdown_function('shutdown');
169 // Make the child the main process, detach it from the terminal
170 if (posix_setsid() < 0) {
174 // Closing all existing connections with the outside
177 // And now connect the database again
181 DI::config()->set('system', 'worker_daemon_mode', true);
183 // Just to be sure that this script really runs endlessly
186 $wait_interval = intval(DI::config()->get('system', 'cron_interval', 5)) * 60;
191 // Now running as a daemon.
193 if (!$do_cron && ($last_cron + $wait_interval) < time()) {
194 Logger::info('Forcing cron worker call.', ["pid" => $pid]);
198 if ($do_cron || (!DI::process()->isMaxLoadReached() && Worker::entriesExists() && Worker::isReady())) {
199 Worker::spawnWorker($do_cron);
201 Logger::info('Cool down for 5 seconds', ['pid' => $pid]);
206 // We force a reconnect of the database connection.
207 // This is done to ensure that the connection don't get lost over time.
214 Logger::info("Sleeping", ["pid" => $pid, 'until' => gmdate(DateTimeFormat::MYSQL, $start + $wait_interval)]);
217 $seconds = (time() - $start);
219 // logarithmic wait time calculation.
220 // Background: After jobs had been started, they often fork many workers.
221 // To not waste too much time, the sleep period increases.
222 $arg = (($seconds + 1) / ($wait_interval / 9)) + 1;
223 $sleep = min(1000000, round(log10($arg) * 1000000, 0));
226 $pid = pcntl_waitpid(-1, $status, WNOHANG);
228 Logger::info('Children quit via pcntl_waitpid', ['pid' => $pid, 'status' => $status]);
231 $timeout = ($seconds >= $wait_interval);
232 } while (!$timeout && !Worker::IPCJobsExists());
236 Logger::info("Woke up after $wait_interval seconds.", ["pid" => $pid, 'sleep' => $wait_interval]);
239 Logger::info("Worker jobs are calling to be forked.", ["pid" => $pid]);
243 function shutdown() {
244 posix_kill(posix_getpid(), SIGHUP);