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