]> git.mxchange.org Git - friendica.git/blob - bin/daemon.php
Update .gitignore for new php-cs-fixer filename
[friendica.git] / bin / daemon.php
1 #!/usr/bin/env php
2 <?php
3 /**
4  * @copyright Copyright (C) 2010-2024, the Friendica project
5  *
6  * @license GNU AGPL version 3 or any later version
7  *
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.
12  *
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.
17  *
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/>.
20  *
21  */
22
23 /**
24  * Run the worker from a daemon.
25  *
26  * This script was taken from http://php.net/manual/en/function.pcntl-fork.php
27  */
28 if (php_sapi_name() !== 'cli') {
29         header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
30         exit();
31 }
32
33 use Dice\Dice;
34 use Friendica\App\Mode;
35 use Friendica\Core\Logger;
36 use Friendica\Core\Update;
37 use Friendica\Core\Worker;
38 use Friendica\Database\DBA;
39 use Friendica\DI;
40 use Friendica\Util\DateTimeFormat;
41 use Psr\Log\LoggerInterface;
42
43 // Get options
44 $shortopts = 'f';
45 $longopts = ['foreground'];
46 $options = getopt($shortopts, $longopts);
47
48 // Ensure that daemon.php is executed from the base path of the installation
49 if (!file_exists('index.php') && (sizeof($_SERVER['argv']) != 0)) {
50         $directory = dirname($_SERVER['argv'][0]);
51
52         if (substr($directory, 0, 1) != '/') {
53                 $directory = $_SERVER['PWD'] . '/' . $directory;
54         }
55         $directory = realpath($directory . '/..');
56
57         chdir($directory);
58 }
59
60 require dirname(__DIR__) . '/vendor/autoload.php';
61
62 $dice = (new Dice())->addRules(include __DIR__ . '/../static/dependencies.config.php');
63 /** @var \Friendica\Core\Addon\Capability\ICanLoadAddons $addonLoader */
64 $addonLoader = $dice->create(\Friendica\Core\Addon\Capability\ICanLoadAddons::class);
65 $dice = $dice->addRules($addonLoader->getActiveAddonConfig('dependencies'));
66 $dice = $dice->addRule(LoggerInterface::class, ['constructParams' => [Logger\Capability\LogChannel::DAEMON]]);
67
68 DI::init($dice);
69 \Friendica\Core\Logger\Handler\ErrorHandler::register($dice->create(\Psr\Log\LoggerInterface::class));
70
71 if (DI::mode()->isInstall()) {
72         die("Friendica isn't properly installed yet.\n");
73 }
74
75 DI::mode()->setExecutor(Mode::DAEMON);
76
77 DI::config()->reload();
78
79 if (empty(DI::config()->get('system', 'pidfile'))) {
80         die(<<<TXT
81 Please set system.pidfile in config/local.config.php. For example:
82
83     'system' => [
84         'pidfile' => '/path/to/daemon.pid',
85     ],
86 TXT
87     );
88 }
89
90 $pidfile = DI::config()->get('system', 'pidfile');
91
92 if (in_array('start', $_SERVER['argv'])) {
93         $mode = 'start';
94 }
95
96 if (in_array('stop', $_SERVER['argv'])) {
97         $mode = 'stop';
98 }
99
100 if (in_array('status', $_SERVER['argv'])) {
101         $mode = 'status';
102 }
103
104 $foreground = array_key_exists('f', $options) || array_key_exists('foreground', $options);
105
106 if (!isset($mode)) {
107         die("Please use either 'start', 'stop' or 'status'.\n");
108 }
109
110 if (empty($_SERVER['argv'][0])) {
111         die("Unexpected script behaviour. This message should never occur.\n");
112 }
113
114 $pid = null;
115
116 if (is_readable($pidfile)) {
117         $pid = intval(file_get_contents($pidfile));
118 }
119
120 if (empty($pid) && in_array($mode, ['stop', 'status'])) {
121         DI::keyValue()->set('worker_daemon_mode', false);
122         die("Pidfile wasn't found. Is the daemon running?\n");
123 }
124
125 if ($mode == 'status') {
126         if (posix_kill($pid, 0)) {
127                 die("Daemon process $pid is running.\n");
128         }
129
130         unlink($pidfile);
131
132         DI::keyValue()->set('worker_daemon_mode', false);
133         die("Daemon process $pid isn't running.\n");
134 }
135
136 if ($mode == 'stop') {
137         posix_kill($pid, SIGTERM);
138
139         unlink($pidfile);
140
141         Logger::notice('Worker daemon process was killed', ['pid' => $pid]);
142
143         DI::keyValue()->set('worker_daemon_mode', false);
144         die("Worker daemon process $pid was killed.\n");
145 }
146
147 if (!empty($pid) && posix_kill($pid, 0)) {
148         die("Daemon process $pid is already running.\n");
149 }
150
151 Logger::notice('Starting worker daemon.', ['pid' => $pid]);
152
153 if (!$foreground) {
154         echo "Starting worker daemon.\n";
155
156         DBA::disconnect();
157
158         // Fork a daemon process
159         $pid = pcntl_fork();
160         if ($pid == -1) {
161                 echo "Daemon couldn't be forked.\n";
162                 Logger::warning('Could not fork daemon');
163                 exit(1);
164         } elseif ($pid) {
165                 // The parent process continues here
166                 if (!file_put_contents($pidfile, $pid)) {
167                         echo "Pid file wasn't written.\n";
168                         Logger::warning('Could not store pid file');
169                         posix_kill($pid, SIGTERM);
170                         exit(1);
171                 }
172                 echo 'Child process started with pid ' . $pid . ".\n";
173                 Logger::notice('Child process started', ['pid' => $pid]);
174                 exit(0);
175         }
176
177         // We now are in the child process
178         register_shutdown_function('shutdown');
179
180         // Make the child the main process, detach it from the terminal
181         if (posix_setsid() < 0) {
182                 return;
183         }
184
185         // Closing all existing connections with the outside
186         fclose(STDIN);
187
188         // And now connect the database again
189         DBA::connect();
190 }
191
192 DI::keyValue()->set('worker_daemon_mode', true);
193
194 // Just to be sure that this script really runs endlessly
195 set_time_limit(0);
196
197 $wait_interval = intval(DI::config()->get('system', 'cron_interval', 5)) * 60;
198
199 $do_cron = true;
200 $last_cron = 0;
201
202 // Now running as a daemon.
203 while (true) {
204         // Check the database structure and possibly fixes it
205         Update::check(DI::basePath(), true);
206
207         if (!$do_cron && ($last_cron + $wait_interval) < time()) {
208                 Logger::info('Forcing cron worker call.', ['pid' => $pid]);
209                 $do_cron = true;
210         }
211
212         if ($do_cron || (!DI::system()->isMaxLoadReached() && Worker::entriesExists() && Worker::isReady())) {
213                 Worker::spawnWorker($do_cron);
214         } else {
215                 Logger::info('Cool down for 5 seconds', ['pid' => $pid]);
216                 sleep(5);
217         }
218
219         if ($do_cron) {
220                 // We force a reconnect of the database connection.
221                 // This is done to ensure that the connection don't get lost over time.
222                 DBA::reconnect();
223
224                 $last_cron = time();
225         }
226
227         $start = time();
228         Logger::info('Sleeping', ['pid' => $pid, 'until' => gmdate(DateTimeFormat::MYSQL, $start + $wait_interval)]);
229
230         do {
231                 $seconds = (time() - $start);
232
233                 // logarithmic wait time calculation.
234                 // Background: After jobs had been started, they often fork many workers.
235                 // To not waste too much time, the sleep period increases.
236                 $arg = (($seconds + 1) / ($wait_interval / 9)) + 1;
237                 $sleep = min(1000000, round(log10($arg) * 1000000, 0));
238                 usleep($sleep);
239
240                 $pid = pcntl_waitpid(-1, $status, WNOHANG);
241                 if ($pid > 0) {
242                         Logger::info('Children quit via pcntl_waitpid', ['pid' => $pid, 'status' => $status]);
243                 }
244
245                 $timeout = ($seconds >= $wait_interval);
246         } while (!$timeout && !Worker\IPC::JobsExists());
247
248         if ($timeout) {
249                 $do_cron = true;
250                 Logger::info('Woke up after $wait_interval seconds.', ['pid' => $pid, 'sleep' => $wait_interval]);
251         } else {
252                 $do_cron = false;
253                 Logger::info('Worker jobs are calling to be forked.', ['pid' => $pid]);
254         }
255 }
256
257 function shutdown() {
258         posix_kill(posix_getpid(), SIGTERM);
259         posix_kill(posix_getpid(), SIGHUP);
260 }