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