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