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