-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPhpServerContext.php
635 lines (542 loc) · 17.6 KB
/
PhpServerContext.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
<?php
declare(strict_types=1);
namespace DrevOps\BehatPhpServer;
use Behat\Behat\Context\Context;
use Behat\Behat\Hook\Scope\AfterScenarioScope;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
/**
* Class PhpServerContext.
*
* Behat context to enable PHPServer support in tests.
*
* @package DrevOps\BehatPhpServer
*/
class PhpServerContext implements Context {
/**
* Tag for scenarios that require this server.
*/
const TAG = 'phpserver';
/**
* Default webroot directory.
*/
const DEFAULT_WEBROOT = __DIR__ . '/fixtures';
/**
* Default connection retry timeout in seconds.
*/
const DEFAULT_CONNECTION_TIMEOUT = 2;
/**
* Default retry delay in microseconds.
*/
const DEFAULT_RETRY_DELAY = 100000;
/**
* Webroot directory.
*/
protected string $webroot;
/**
* Server hostname.
*/
protected string $host;
/**
* Server port.
*/
protected int $port;
/**
* Server protocol.
*/
protected string $protocol;
/**
* Server process id.
*/
protected int $pid = 0;
/**
* Debug mode.
*/
protected bool $debug = FALSE;
/**
* Connection retry timeout in seconds.
*/
protected int $connectionTimeout;
/**
* Retry delay in microseconds.
*/
protected int $retryDelay;
/**
* PhpServerTrait constructor.
*
* @param string|null $webroot
* Webroot directory.
* @param string $host
* Server hostname.
* @param int $port
* Server port.
* @param string $protocol
* Server protocol.
* @param bool $debug
* Debug mode.
* @param int|null $connection_timeout
* Connection retry timeout in seconds.
* @param int|null $retry_delay
* Retry delay in microseconds.
*/
public function __construct(
?string $webroot = NULL,
string $host = '127.0.0.1',
int $port = 8888,
string $protocol = 'http',
bool $debug = FALSE,
?int $connection_timeout = NULL,
?int $retry_delay = NULL,
) {
$this->webroot = $webroot ?: static::DEFAULT_WEBROOT;
if (!file_exists($this->webroot)) {
throw new \RuntimeException(sprintf('"webroot" directory %s does not exist', $this->webroot));
}
$this->host = $host;
$this->port = $port;
$this->protocol = $protocol;
$this->debug = $debug;
$this->connectionTimeout = $connection_timeout ?? static::DEFAULT_CONNECTION_TIMEOUT;
$this->retryDelay = $retry_delay ?? static::DEFAULT_RETRY_DELAY;
}
/**
* Get server URL.
*
* @return string
* Server URL.
*/
public function getServerUrl(): string {
return $this->protocol . '://' . $this->host . ':' . $this->port;
}
/**
* Start server before each scenario.
*
* @param \Behat\Behat\Hook\Scope\BeforeScenarioScope $scope
* Scenario scope.
*
* @beforeScenario
*/
public function beforeScenarioStartServer(BeforeScenarioScope $scope): void {
if ($scope->getScenario()->hasTag(static::TAG)) {
$this->start();
}
}
/**
* Stop server after each scenario.
*
* @param \Behat\Behat\Hook\Scope\AfterScenarioScope $scope
* Scenario scope.
*
* @afterScenario
*/
public function afterScenarioStopServer(AfterScenarioScope $scope): void {
if ($scope->getScenario()->hasTag(static::TAG)) {
$this->stop();
}
}
/**
* Start a server.
*
* @return int
* PID as number.
*
* @throws \RuntimeException
* If unable to start a server.
*/
public function start(): int {
// Make sure any existing server is stopped.
if (!$this->stop()) {
throw new \RuntimeException(sprintf('Unable to stop existing server on port %d.', $this->port));
}
$command = sprintf(
// Pass a random process ID to the server so it can be accessed from
// within the scripts.
'PROCESS_TIMESTAMP=%s php -S %s:%d -t %s >/dev/null 2>&1 & echo $!',
microtime(TRUE),
$this->host,
$this->port,
$this->webroot
);
$this->debug(sprintf('Starting PHP server with command: %s', $command));
$output = [];
$code = 0;
$success = $this->executeCommand($command, $output, $code);
if ($success && !empty($output[0]) && is_numeric($output[0])) {
$this->pid = (int) $output[0];
}
else {
$this->debug(sprintf('Command execution failed with code %d or empty/invalid output: %s', $code, implode(', ', $output)));
throw new \RuntimeException(sprintf('Unable to start PHP server: Command failed with code %d', $code));
}
$this->debug(sprintf('PHP server started with PID %s.', $this->pid));
if (!$this->isRunning()) {
$this->stop();
throw new \RuntimeException(sprintf(
'PHP server failed to start or accept connections within %d seconds.',
$this->connectionTimeout
));
}
$this->debug('PHP server is now running and accepting connections.');
return $this->pid;
}
/**
* Stop running server.
*
* @return bool
* TRUE if server process was stopped, FALSE otherwise.
*/
public function stop(): bool {
if ($this->pid !== 0 && $this->processExists($this->pid)) {
$this->debug(sprintf('Terminating known process with PID %d.', $this->pid));
if ($this->terminateProcess($this->pid)) {
$this->debug('Successfully terminated process.');
$this->pid = 0;
}
}
try {
// Check if port is still in use.
if ($this->isPortInUse($this->port)) {
$this->debug(sprintf('Port %d is still in use. Attempting to free it.', $this->port));
$port_freed = $this->freePort($this->port);
if (!$port_freed) {
$this->debug(sprintf('Failed to free port %d. Free port function returned failure.', $this->port));
return FALSE;
}
// Double-check the port is actually free now.
if ($this->isPortInUse($this->port)) {
$this->debug(sprintf('Failed to free port %d. Port is still in use after freeing attempt.', $this->port));
return FALSE;
}
$this->debug(sprintf('Successfully freed port %d.', $this->port));
}
else {
$this->debug(sprintf('Port %d is already free.', $this->port));
}
}
catch (\Exception $exception) {
$this->debug(sprintf('Error while trying to stop server: %s', $exception->getMessage()));
return FALSE;
}
$this->pid = 0;
return TRUE;
}
/**
* Check that a server is running.
*
* @param int|null $timeout
* Retry timeout in seconds. If NULL, use the configured timeout.
* @param int|null $retry_delay
* Delay between retries in microseconds. If NULL, use the configured delay.
*
* @return bool
* TRUE if the server is running, FALSE otherwise.
*/
protected function isRunning(?int $timeout = NULL, ?int $retry_delay = NULL): bool {
$timeout = $timeout ?? $this->connectionTimeout;
$retry_delay = $retry_delay ?? $this->retryDelay;
$start = microtime(TRUE);
// First, if we have a PID, check if the process is actually running.
if ($this->pid > 0 && !$this->processExists($this->pid)) {
return FALSE;
}
// Next, try to make a connection to verify server is accepting connections.
$counter = 1;
while ((microtime(TRUE) - $start) <= $timeout) {
$this->debug(sprintf('Checking if server is running. Attempt %s.', $counter));
if ($this->canConnect()) {
$this->debug('Server is running and accepting connections.');
return TRUE;
}
usleep($retry_delay);
$counter++;
}
$this->debug('Server is not responding to connection attempts.');
return FALSE;
}
/**
* Check if a port is already in use.
*
* @param int $port
* The port to check.
*
* @return bool
* TRUE if the port is in use, FALSE otherwise.
*/
protected function isPortInUse(int $port): bool {
$this->debug(sprintf('Checking if port %d is already in use.', $port));
// Temporarily suppress errors.
set_error_handler(static function (): bool {
return TRUE;
});
// Use very short timeout to avoid hanging.
$connection = @fsockopen(
$this->host === '0.0.0.0' ? '127.0.0.1' : $this->host,
$port,
$errno,
$errstr,
0.1
);
// Restore error handler.
restore_error_handler();
// If connection succeeded, the port is in use.
if ($connection !== FALSE) {
fclose($connection);
$this->debug(sprintf('Port %d is already in use (connection succeeded).', $port));
return TRUE;
}
// If connection failed because the port is unreachable, it's not in use.
// Error 111 = Connection refused (Linux)
// Error 10061 = Connection refused (Windows)
$connection_refused = in_array($errno, [61, 111, 10061], TRUE);
if ($connection_refused) {
$this->debug(sprintf('Port %d is available (connection refused).', $port));
return FALSE;
}
// For any other errors, assume the port is in use to be safe.
$this->debug(sprintf('Port %d status check resulted in error %d: %s. Assuming it is in use.', $port, $errno, $errstr));
return TRUE;
}
/**
* Attempt to free a port that's in use.
*
* @param int $port
* The port to free.
*
* @return bool
* TRUE if the port was successfully freed or no process was found,
* FALSE if there was an error or the process could not be terminated.
*/
protected function freePort(int $port): bool {
$this->debug(sprintf('Attempting to free port %d.', $port));
try {
$pid = $this->getPid($port);
if ($pid > 0) {
$this->debug(sprintf('Found process with PID %d using port %d.', $pid, $port));
$result = $this->terminateProcess($pid);
// Verify the port is now free.
$is_free = !$this->isPortInUse($port);
if (!$is_free) {
$this->debug(sprintf('Port %d is still in use after terminating process %d.', $port, $pid));
return FALSE;
}
return $result;
}
// No process found, consider the port free.
return TRUE;
}
catch (\Exception $exception) {
$this->debug(sprintf('Error while trying to free port %d: %s', $port, $exception->getMessage()));
return FALSE;
}
}
/**
* Check if it is possible to connect to a running PHP server.
*
* @param int|null $timeout
* Connection timeout in seconds. If NULL, use the configured timeout.
*
* @return bool
* TRUE if PHP server is running, and it is possible to connect to it via
* socket, FALSE otherwise.
*/
protected function canConnect(?int $timeout = NULL): bool {
$timeout = $timeout ?? $this->connectionTimeout;
set_error_handler(
static function (): bool {
return TRUE;
}
);
// Use timeout to avoid hanging connections.
$sp = @fsockopen($this->host, $this->port, $errno, $errstr, $timeout);
restore_error_handler();
if ($sp === FALSE) {
$this->debug(sprintf('Unable to connect to the server. Error: %s (%s)', $errstr, $errno));
return FALSE;
}
fclose($sp);
$this->debug('Connected to the server.');
return TRUE;
}
/**
* Terminate a process.
*
* @param int $pid
* Process id.
*
* @return bool
* TRUE if the process was successfully terminated, FALSE otherwise.
*/
protected function terminateProcess(int $pid): bool {
$termination_status = 'unknown';
$this->debug(sprintf('Terminating PHP server process with PID %s.', $pid));
// First check if the process exists.
if (!$this->processExists($pid)) {
$this->debug(sprintf('Process with PID %d does not exist, no need to terminate.', $pid));
return TRUE;
}
$output = [];
// First try graceful termination (SIGTERM).
$success = $this->executeCommand('kill ' . $pid . ' 2>/dev/null', $output);
if (!$success) {
$this->debug('Graceful termination failed, trying forceful termination (SIGKILL).');
// If the first attempt fails, try force kill.
$success = $this->executeCommand('kill -9 ' . $pid . ' 2>/dev/null', $output);
$termination_status = $success ? 'forceful' : 'failed';
}
else {
$termination_status = 'graceful';
}
// Wait a short time for the process to terminate.
usleep($this->retryDelay);
// Verify process is actually gone.
if ($this->processExists($pid)) {
$this->debug(sprintf(
'Process termination verification failed (%s termination status), process may still be running.',
$termination_status
));
return FALSE;
}
$this->debug(sprintf('Process terminated successfully with %s termination.', $termination_status));
return $success;
}
/**
* Check if a process exists.
*
* @param int $pid
* Process id to check.
*
* @return bool
* TRUE if the process exists, FALSE otherwise.
*/
protected function processExists(int $pid): bool {
if ($pid <= 0) {
return FALSE;
}
$output = [];
$this->executeCommand('ps -p ' . $pid . ' 2>/dev/null', $output);
$is_running = count($output) > 1;
if (!$is_running) {
$this->debug(sprintf('Process with PID %d is not running.', $pid));
}
return $is_running;
}
/**
* Get PID of the running server on the specified port.
*
* Note that this will retrieve a PID of the process that could have been
* started by another process rather then current one.
*
* @param int $port
* Port number.
*
* @return int
* PID as number.
*/
protected function getPid(int $port): int {
$pid = 0;
$this->debug(sprintf('Finding PID of the PHP server process on port %s.', $port));
// First, try with the stored PID if we have one.
if ($this->pid > 0 && $this->processExists($this->pid)) {
$this->debug(sprintf('Found existing process with PID %s is still running.', $this->pid));
return $this->pid;
}
// Determine which command to use based on OS.
$command = NULL;
$type = NULL;
if ($this->executeCommand('which lsof 2>/dev/null')) {
$command = sprintf("lsof -i -P -n 2>/dev/null | grep 'php' | grep ':%s' | grep 'LISTEN'", $port);
$type = 'lsof';
}
elseif ($this->executeCommand('which netstat 2>/dev/null')) {
$command = sprintf("netstat -an 2>/dev/null | grep ':%s' | grep 'LISTEN'", $port);
$type = 'netstat';
}
else {
$this->debug('No supported OS utilities found for process detection.');
throw new \RuntimeException('Unable to determine if PHP server was started: no supported OS utilities found. Manually identify the process and terminate it.');
}
$this->debug(sprintf('Using "%s" command to find the PID.', $command));
$output = [];
$this->executeCommand($command, $output);
if (empty($output)) {
// Try without the LISTEN filter in case the process is in another state.
$command = str_replace(" | grep 'LISTEN'", '', $command);
$this->debug(sprintf('No LISTEN processes found, retrying with command: %s', $command));
$this->executeCommand($command, $output);
}
if (empty($output)) {
$this->debug('No processes found on port ' . $port);
throw new \RuntimeException(sprintf('Unable to find PHP server process on port %s.', $port));
}
// Log all found processes.
foreach ($output as $i => $line) {
$this->debug(sprintf('Found process %d: %s', $i + 1, $line));
}
// Try to find PHP process among the results.
foreach ($output as $line) {
$line = preg_replace('/\s+/', ' ', $line);
$this->debug(sprintf('Processing line: %s', $line));
$parts = explode(' ', (string) $line);
if ($type === 'lsof') {
if (count($parts) > 1 && $parts[0] === 'php' && is_numeric($parts[1])) {
$pid = intval($parts[1]);
$this->debug(sprintf('Found PHP process with PID %s using lsof.', $pid));
break;
}
}
elseif ($type === 'netstat') {
if (isset($parts[8]) && strpos($parts[8], '/php') !== FALSE) {
$part8 = $parts[8];
$pid_name_parts = explode('/', $part8);
if (count($pid_name_parts) > 1) {
$found_pid = $pid_name_parts[0];
$name = $pid_name_parts[1];
if (is_numeric($found_pid) && strpos($name, 'php') === 0) {
$pid = intval($found_pid);
$this->debug(sprintf('Found PHP process with PID %s using netstat.', $pid));
break;
}
}
}
}
}
if ($pid === 0) {
$this->debug('Could not identify PHP process from output: ' . implode("\n", $output));
throw new \RuntimeException(sprintf('Unable to determine if PHP server was started: PID is 0 in command "%s" output. Manually identify the process and terminate it.', $command));
}
return $pid;
}
/**
* Execute a shell command and return the exit code.
*
* @param string $command
* The command to execute.
* @param array<string> $output
* An array that will be filled with the output of the command.
* @param int $code
* The return status of the executed command.
*
* @return bool
* TRUE if the command was executed successfully, FALSE otherwise.
*/
protected function executeCommand(string $command, array &$output = [], int &$code = 0): bool {
// @codeCoverageIgnoreStart
exec($command, $output, $code);
return !$code;
// @codeCoverageIgnoreEnd
}
/**
* Print debug message if debug mode is enabled.
*
* @param string $message
* Message to print.
*/
protected function debug(string $message): void {
// @codeCoverageIgnoreStart
if ($this->debug) {
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
$caller = $backtrace[1]['function'] ?? 'unknown';
print sprintf('[%s()] %s', $caller, $message) . PHP_EOL;
}
// @codeCoverageIgnoreEnd
}
}