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