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