Merge pull request #9208 from tobiasd/2020.09-creadits
[friendica.git/.git] / bin / daemon.php
1 #!/usr/bin/env php
2 <?php
3 /**
4  * @copyright Copyright (C) 2020, Friendica
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\Core\Logger;
33 use Friendica\Core\Worker;
34 use Friendica\Database\DBA;
35 use Friendica\DI;
36 use Psr\Log\LoggerInterface;
37
38 // Get options
39 $shortopts = 'f';
40 $longopts = ['foreground'];
41 $options = getopt($shortopts, $longopts);
42
43 // Ensure that daemon.php is executed from the base path of the installation
44 if (!file_exists("boot.php") && (sizeof($_SERVER["argv"]) != 0)) {
45         $directory = dirname($_SERVER["argv"][0]);
46
47         if (substr($directory, 0, 1) != "/") {
48                 $directory = $_SERVER["PWD"] . "/" . $directory;
49         }
50         $directory = realpath($directory . "/..");
51
52         chdir($directory);
53 }
54
55 require dirname(__DIR__) . '/vendor/autoload.php';
56
57 $dice = (new Dice())->addRules(include __DIR__ . '/../static/dependencies.config.php');
58 $dice = $dice->addRule(LoggerInterface::class,['constructParams' => ['daemon']]);
59
60 DI::init($dice);
61 $a = DI::app();
62
63 if (DI::mode()->isInstall()) {
64         die("Friendica isn't properly installed yet.\n");
65 }
66
67 DI::config()->load();
68
69 if (empty(DI::config()->get('system', 'pidfile'))) {
70         die(<<<TXT
71 Please set system.pidfile in config/local.config.php. For example:
72     
73     'system' => [ 
74         'pidfile' => '/path/to/daemon.pid',
75     ],
76 TXT
77     );
78 }
79
80 $pidfile = DI::config()->get('system', 'pidfile');
81
82 if (in_array("start", $_SERVER["argv"])) {
83         $mode = "start";
84 }
85
86 if (in_array("stop", $_SERVER["argv"])) {
87         $mode = "stop";
88 }
89
90 if (in_array("status", $_SERVER["argv"])) {
91         $mode = "status";
92 }
93
94 $foreground = array_key_exists('f', $options) || array_key_exists('foreground', $options);
95
96 if (!isset($mode)) {
97         die("Please use either 'start', 'stop' or 'status'.\n");
98 }
99
100 if (empty($_SERVER["argv"][0])) {
101         die("Unexpected script behaviour. This message should never occur.\n");
102 }
103
104 $pid = null;
105
106 if (is_readable($pidfile)) {
107         $pid = intval(file_get_contents($pidfile));
108 }
109
110 if (empty($pid) && in_array($mode, ["stop", "status"])) {
111         DI::config()->set('system', 'worker_daemon_mode', false);
112         die("Pidfile wasn't found. Is the daemon running?\n");
113 }
114
115 if ($mode == "status") {
116         if (posix_kill($pid, 0)) {
117                 die("Daemon process $pid is running.\n");
118         }
119
120         unlink($pidfile);
121
122         DI::config()->set('system', 'worker_daemon_mode', false);
123         die("Daemon process $pid isn't running.\n");
124 }
125
126 if ($mode == "stop") {
127         posix_kill($pid, SIGTERM);
128
129         unlink($pidfile);
130
131         Logger::notice("Worker daemon process was killed", ["pid" => $pid]);
132
133         DI::config()->set('system', 'worker_daemon_mode', false);
134         die("Worker daemon process $pid was killed.\n");
135 }
136
137 if (!empty($pid) && posix_kill($pid, 0)) {
138         die("Daemon process $pid is already running.\n");
139 }
140
141 Logger::notice('Starting worker daemon.', ["pid" => $pid]);
142
143 if (!$foreground) {
144         echo "Starting worker daemon.\n";
145
146         // Switch over to daemon mode.
147         if ($pid = pcntl_fork()) {
148                 return;     // Parent
149         }
150
151         fclose(STDIN);  // Close all of the standard
152
153         // Enabling this seem to block a running php process with 100% CPU usage when there is an outpout
154         // fclose(STDOUT); // file descriptors as we
155         // fclose(STDERR); // are running as a daemon.
156
157         DBA::disconnect();
158
159         register_shutdown_function('shutdown');
160
161         if (posix_setsid() < 0) {
162                 return;
163         }
164
165         if ($pid = pcntl_fork()) {
166                 return;     // Parent
167         }
168
169         $pid = getmypid();
170         file_put_contents($pidfile, $pid);
171
172         // We lose the database connection upon forking
173         DBA::reconnect();
174 }
175
176 DI::config()->set('system', 'worker_daemon_mode', true);
177
178 // Just to be sure that this script really runs endlessly
179 set_time_limit(0);
180
181 $wait_interval = intval(DI::config()->get('system', 'cron_interval', 5)) * 60;
182
183 $do_cron = true;
184 $last_cron = 0;
185
186 // Now running as a daemon.
187 while (true) {
188         if (!$do_cron && ($last_cron + $wait_interval) < time()) {
189                 Logger::info('Forcing cron worker call.', ["pid" => $pid]);
190                 $do_cron = true;
191         }
192
193         if ($do_cron || (!DI::process()->isMaxLoadReached() && Worker::entriesExists() && Worker::isReady())) {
194                 Worker::spawnWorker($do_cron);
195         } else {
196                 Logger::info('Cool down', ['pid' => $pid]);
197                 sleep(10);
198         }
199
200         if ($do_cron) {
201                 // We force a reconnect of the database connection.
202                 // This is done to ensure that the connection don't get lost over time.
203                 DBA::reconnect();
204
205                 $last_cron = time();
206         }
207
208         Logger::info("Sleeping", ["pid" => $pid]);
209         $start = time();
210         do {
211                 $seconds = (time() - $start);
212
213                 // logarithmic wait time calculation.
214                 // Background: After jobs had been started, they often fork many workers.
215                 // To not waste too much time, the sleep period increases.
216                 $arg = (($seconds + 1) / ($wait_interval / 9)) + 1;
217                 $sleep = round(log10($arg) * 1000000, 0);
218                 usleep($sleep);
219
220                 $timeout = ($seconds >= $wait_interval);
221         } while (!$timeout && !Worker::IPCJobsExists());
222
223         if ($timeout) {
224                 $do_cron = true;
225                 Logger::info("Woke up after $wait_interval seconds.", ["pid" => $pid, 'sleep' => $wait_interval]);
226         } else {
227                 $do_cron = false;
228                 Logger::info("Worker jobs are calling to be forked.", ["pid" => $pid]);
229         }
230 }
231
232 function shutdown() {
233         posix_kill(posix_getpid(), SIGHUP);
234 }