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