Completed
Push — master ( 8da12a...178c32 )
by Sébastien
14:05 queued 11:13
created

StandaloneServer::getCommand()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 36
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 5.0909

Importance

Changes 0
Metric Value
dl 0
loc 36
ccs 22
cts 26
cp 0.8462
rs 8.439
c 0
b 0
f 0
cc 5
eloc 23
nc 5
nop 0
crap 5.0909
1
<?php
2
3
namespace PjbServer\Tools;
4
5
use PjbServer\Tools\Network\PortTester;
6
use PjbServer\Tools\System\Process;
7
use Psr\Log\LoggerInterface;
8
use Psr\Log\NullLogger;
9
10
class StandaloneServer
11
{
12
    /**
13
     * @var int
14
     */
15
    protected $port;
16
17
    /**
18
     * @var StandaloneServer\Config
19
     */
20
    protected $config;
21
22
    /**
23
     * Tells whether the standalone server is started.
24
     *
25
     * @var bool
26
     */
27
    protected $started = false;
28
29
    /**
30
     * @var PortTester
31
     */
32
    protected $portTester;
33
34
    /**
35
     * @var LoggerInterface
36
     */
37
    protected $logger;
38
39
    /**
40
     * @var Process
41
     */
42
    protected $process;
43
44
    /**
45
     * Constructor.
46
     *
47
     * <code>
48
     *
49
     * $config = array(
50
     *      'port' => 8089,
51
     *
52
     *      // optionally
53
     *      'server_jar' => 'path/to/JavaBridge.jar'
54
     *      'java_bin' => 'path/to/java'
55
     * );
56
     * $server = new StandaloneServer($config);
57
     *
58
     * </code>
59
     *
60
     * @throws Exception\InvalidArgumentException
61
     *
62
     * @param StandaloneServer\Config $config
63
     * @param LoggerInterface         $logger
64
     */
65 22
    public function __construct(StandaloneServer\Config $config, LoggerInterface $logger = null)
66
    {
67 22
        $this->config = $config;
68
69 22
        $curl_available = function_exists('curl_version');
70
71 22
        $this->portTester = new PortTester([
72 22
            'backend' => $curl_available ? PortTester::BACKEND_CURL : PortTester::BACKEND_STREAM_SOCKET,
73
            // Close timout ms could be adjusted for your system
74
            // It prevent that port availability testing does
75
            // not close quickly enough to allow standalone server binding
76 22
            'close_timeout_ms' => $curl_available ? null : 300
77 22
        ]);
78 22
        if ($logger === null) {
79 15
            $logger = new NullLogger();
80 15
        }
81 22
        $this->logger = $logger;
82
83 22
        $this->process = new Process();
84 22
    }
85
86
    /**
87
     * Start the standalone server.
88
     *
89
     * @throws Exception\RuntimeException
90
     *
91
     * @param int $timeout_ms maximum number of milliseconds to wait for server start
92
     */
93 14
    public function start($timeout_ms = 3000)
94
    {
95 14
        $port = $this->config->getPort();
96
97 14
        $this->logger->notice("Starting standalone server on port $port.");
98
99 14
        if ($this->isStarted()) {
100 2
            $this->logger->notice('Standalone server already running, skipping start.');
101
102 2
            return;
103
        }
104
105 14
        if (!$this->portTester->isAvailable('localhost', $port, 'http')) {
106 1
            $msg = "Cannot start server on port '$port', it's already in use.";
107 1
            $this->logger->error("Start failed: $msg");
108 1
            throw new Exception\PortUnavailableException($msg);
109
        }
110
111 14
        $command = $this->getCommand();
112
113 14
        $log_file = $this->config->getLogFile();
114 14
        $pid_file = $this->config->getPidFile();
115 14
        $cmd = sprintf('%s > %s 2>&1 & echo $! > %s', $command, $log_file, $pid_file);
116
117 14
        $this->logger->debug("Start server with: $cmd");
118 14
        exec($cmd);
119
120 14
        if (!file_exists($pid_file)) {
121
            $msg = "Server not started, pid file was not created in '$pid_file'";
122
            $this->logger->error("Start failed: $msg");
123
            throw new Exception\RuntimeException($msg);
124
        }
125 14
        if (!file_exists($log_file)) {
126
            $msg = "Server not started, log file was not created in '$log_file'";
127
            $this->logger->error("Start failed: $msg");
128
            throw new Exception\RuntimeException($msg);
129
        }
130
131
        // Loop for waiting correct start of phpjavabridge
132 14
        $started = false;
133 14
        $iterations = true;
134 14
        $refresh_us = 100 * 1000; // 100ms
135 14
        $timeout_us = $timeout_ms * 1000;
136 14
        $max_iterations = ceil($timeout_us / min([$refresh_us, $timeout_us]));
137
138 14
        while (!$started || $iterations > $max_iterations) {
139 14
            usleep($refresh_us);
140 14
            $log_file_content = file_get_contents($log_file);
141 14
            if (preg_match('/Exception/', $log_file_content)) {
142
                $msg = "Cannot start standalone server on port '$port', reason:\n";
143
                $msg .= $log_file_content;
144
                $this->logger->error("Start failed: $msg");
145
                throw new Exception\RuntimeException($msg);
146
            }
147
148 14
            $log_file_content = file_get_contents($log_file);
149 14
            if (preg_match('/JavaBridgeRunner started on/', $log_file_content)) {
150 14
                $started = true;
151 14
            }
152 14
            ++$iterations;
153 14
        }
154 14
        if (!$started) {
155
            $msg = "Standalone server probably not started, timeout '$timeout_ms' reached before getting output";
156
            $this->logger->error("Start failed: $msg");
157
            throw new Exception\RuntimeException($msg);
158
        }
159 14
        $this->started = true;
160 14
    }
161
162
    /**
163
     * Stop the standalone server.
164
     *
165
     * @throws Exception\StopFailedException
166
     *
167
     * @param bool $throwException          whether to throw exception if pid exists in config but process cannot be found
168
     * @param bool $clearPidFileOnException clear th pid file if the server was not running
169
     */
170 17
    public function stop($throwException = false, $clearPidFileOnException = false)
171
    {
172 17
        $this->logger->notice('Stopping server');
173
174
        try {
175 17
            $pid = $this->getPid();
176 14
            $running = $this->isProcessRunning(true);
177 14
            if (!$running) {
178
                if ($throwException) {
179
                    $msg = "Cannot stop: pid exists (${pid}) but server process is not running (throws_exception=true)";
180
                    $this->logger->notice("Stop failed: ${msg}");
181
                    throw new Exception\StopFailedException($msg);
182
                }
183
184
                return;
185
            }
186
        } catch (Exception\PidNotFoundException $e) {
187 11
            if ($throwException) {
188 1
                $msg = 'Cannot stop server: pid file not found (was the server started ?)';
189 1
                $this->logger->notice("Stop failed: $msg");
190 1
                if ($clearPidFileOnException) {
191
                    $this->clearPidFile();
192
                }
193 1
                throw new Exception\StopFailedException($msg, null, $e);
194
            }
195
196 11
            return;
197
        }
198
199 14
        $killed = $this->process->kill($pid, true);
200
201
        try {
202 14
            if (!$killed) {
203
                $msg = "Cannot kill standalone server process '$pid', seems to not exists.";
204
                $this->logger->notice("Stop failed: $msg");
205
                throw new Exception\RuntimeException($msg);
206
            }
207 14
        } catch (Exception\RuntimeException $e) {
208
            if ($throwException) {
209
                $this->clearPidFile();
210
                throw $e;
211
            }
212
        }
213
214
        // Server successfully stopped let's clear the pid
215 14
        $this->clearPidFile();
216 14
        $this->started = false;
217 14
    }
218
219
    /**
220
     * @throws Exception\FilePermissionException
221
     */
222
    protected function clearPidFile()
223
    {
224 14
        $pid_file = $this->config->getPidFile();
225 14
        if (file_exists($pid_file)) {
226 14
            if (is_writable($pid_file)) {
227 14
                unlink($pid_file);
228 14
            } else {
229
                throw new Exception\FilePermissionException("Cannot remove pid file '${pid_file}', no write access");
230
            }
231 14
        }
232 14
    }
233
234
    /**
235
     * Tells whether the standalone server is started.
236
     *
237
     * @param bool $test_is_running
238
     *
239
     * @return bool
240
     */
241
    public function isStarted($test_is_running = true)
242
    {
243
        // In case of previous run, let's us
244 14
        if (!$this->started && $test_is_running) {
245 14
            $this->started = $this->isProcessRunning();
246 14
        }
247
248 14
        return $this->started;
249
    }
250
251
    /**
252
     * Return command used to start the standalone server.
253
     *
254
     * @return string
255
     */
256
    public function getCommand()
257
    {
258 15
        $port = $this->config->getPort();
259
260 15
        $java_bin = $this->config->getJavaBin();
261
262 15
        $jars = [];
263 15
        $classpaths = $this->config->getClasspaths();
264 15
        foreach ($classpaths as $classpath) {
265 12
            if (preg_match('/\*\.jar$/', $classpath)) {
266 12
                $directory = preg_replace('/\*\.jar$/', '', $classpath);
267 12
                $files = glob("$directory/*.jar");
268 12
                foreach ($files as $file) {
269
                    foreach ($files as $file) {
270
                        $jars[] = $file;
271
                    }
272 12
                }
273 12
            } else {
274
                $jars[] = $classpath;
275
            }
276 15
        }
277
278 15
        $jars[] = $this->config->getServerJar();
279 15
        $classpath = implode(':', $jars);
280 15
        $threads = $this->config->getThreads();
281
282 15
        $directives = ' -D' . implode(' -D', [
283 15
                    'php.java.bridge.daemon="false"',
284 15
                    "php.java.bridge.threads=$threads"
285 15
        ]);
286
287 15
        $command = sprintf('%s -cp "%s" %s php.java.bridge.Standalone SERVLET:%d',
288 15
                            $java_bin, $classpath, $directives, $port);
289
290 15
        return $command;
291
    }
292
293
    /**
294
     * Get standalone server pid number as it was stored during last start.
295
     *
296
     * @throws Exception\PidNotFoundException|ExceptionPidCorruptedException
297
     *
298
     * @return int
299
     */
300
    public function getPid()
301
    {
302 20
        $pid_file = $this->config->getPidFile();
303 20
        if (!file_exists($pid_file)) {
304 18
            $msg = "Pid file cannot be found '$pid_file'";
305 18
            $this->logger->info("Get PID failed: $msg");
306 18
            throw new Exception\PidNotFoundException($msg);
307
        }
308 15
        $pid = trim(file_get_contents($pid_file));
309 15
        if (!preg_match('/^[0-9]+$/', $pid)) {
310 1
            $msg = "Pid found '$pid_file' but no valid pid stored in it or corrupted file '$pid_file'.";
311 1
            $this->logger->error("Get PID failed: $msg");
312 1
            throw new Exception\PidCorruptedException($msg);
313
        }
314
315 15
        return (int) $pid;
316
    }
317
318
    /**
319
     * Return the content of the output_file.
320
     *
321
     * @throws Exception\RuntimeException
322
     *
323
     * @return string
324
     */
325
    public function getOutput()
326
    {
327 5
        $log_file = $this->config->getLogFile();
328 5
        if (!file_exists($log_file)) {
329 1
            $msg = "Server output log file does not exists '$log_file'";
330 1
            $this->logger->error("Get server output failed: $msg");
331 1
            throw new Exception\RuntimeException($msg);
332 4
        } elseif (!is_readable($log_file)) {
333 1
            $msg = "Cannot read log file do to missing read permission '$log_file'";
334 1
            $this->logger->error("Get server output failed: $msg");
335 1
            throw new Exception\RuntimeException($msg);
336
        }
337 4
        $output = file_get_contents($log_file);
338
339 4
        return $output;
340
    }
341
342
    /**
343
     * Test whether the standalone server process
344
     * is effectively running.
345
     *
346
     * @throws Exception\PidNotFoundException
347
     *
348
     * @param bool $throwsException if false discard exception if pidfile not exists
349
     *
350
     * @return bool
351
     */
352
    public function isProcessRunning($throwsException = false)
353
    {
354 17
        $running = false;
355
        try {
356 17
            $pid = $this->getPid();
357 15
            $isRunning = $this->process->isRunning($pid);
358 15
            if ($isRunning) {
359 15
                $this->logger->debug("Pid '${pid}' running.");
360 15
                $running = true;
361 15
            } else {
362
                $this->logger->debug("Pid '${pid}' not running.");
363
            }
364 17
        } catch (Exception\PidNotFoundException $e) {
365 15
            if ($throwsException) {
366 1
                throw $e;
367
            }
368
        }
369
370 16
        return $running;
371
    }
372
373
    /**
374
     * Restart the standalone server.
375
     */
376
    public function restart()
377
    {
378 3
        $this->stop();
379 3
        $this->start();
380 3
    }
381
382
    /**
383
     * Return underlying configuration object.
384
     *
385
     * @return StandaloneServer\Config
386
     */
387
    public function getConfig()
388
    {
389 14
        return $this->config;
390
    }
391
}
392