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