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