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