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