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