summaryrefslogtreecommitdiff
path: root/sapi/fpm/tests/tester.inc
blob: 7aab2d3aa9d11856282d7adcbbd02be86747fb77 (plain)
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
<?php

namespace FPM;

use Adoy\FastCGI\Client;

require_once 'fcgi.inc';
require_once 'logtool.inc';
require_once 'response.inc';

class Tester
{
    /**
     * Config directory for included files.
     */
    const CONF_DIR = __DIR__ . '/conf.d';

    /**
     * File extension for access log.
     */
    const FILE_EXT_LOG_ACC = 'acc.log';

    /**
     * File extension for error log.
     */
    const FILE_EXT_LOG_ERR = 'err.log';

    /**
     * File extension for slow log.
     */
    const FILE_EXT_LOG_SLOW = 'slow.log';

    /**
     * File extension for PID file.
     */
    const FILE_EXT_PID = 'pid';

    /**
     * @var array
     */
    static private $supportedFiles = [
        self::FILE_EXT_LOG_ACC,
        self::FILE_EXT_LOG_ERR,
        self::FILE_EXT_LOG_SLOW,
        self::FILE_EXT_PID,
        'src.php',
        'ini',
        'skip.ini',
        '*.sock',
    ];

    /**
     * @var array
     */
    static private $filesToClean = ['.user.ini'];

    /**
     * @var bool
     */
    private $debug;

    /**
     * @var array
     */
    private $clients;

    /**
     * @var LogTool
     */
    private $logTool;

    /**
     * Configuration template
     *
     * @var string|array
     */
    private $configTemplate;

    /**
     * The PHP code to execute
     *
     * @var string
     */
    private $code;

    /**
     * @var array
     */
    private $options;

    /**
     * @var string
     */
    private $fileName;

    /**
     * @var resource
     */
    private $masterProcess;

    /**
     * @var resource
     */
    private $outDesc;

    /**
     * @var array
     */
    private $ports = [];

    /**
     * @var string
     */
    private $error;

    /**
     * The last response for the request call
     *
     * @var Response
     */
    private $response;

    /**
     * Clean all the created files up
     *
     * @param int $backTraceIndex
     */
    static public function clean($backTraceIndex = 1)
    {
        $filePrefix = self::getCallerFileName($backTraceIndex);
        if (substr($filePrefix, -6) === 'clean.') {
            $filePrefix = substr($filePrefix, 0, -6);
        }

        $filesToClean = array_merge(
            array_map(
                function($fileExtension) use ($filePrefix) {
                    return $filePrefix . $fileExtension;
                },
                self::$supportedFiles
            ),
            array_map(
                function($fileExtension) {
                    return __DIR__ . '/' . $fileExtension;
                },
                self::$filesToClean
            )
        );
        // clean all the root files
        foreach ($filesToClean as $filePattern) {
            foreach (glob($filePattern) as $filePath) {
                unlink($filePath);
            }
        }

        self::cleanConfigFiles();
    }

    /**
     * Clean config files
     */
    static public function cleanConfigFiles() {
        if (is_dir(self::CONF_DIR)) {
            foreach(glob(self::CONF_DIR . '/*.conf') as $name) {
                unlink($name);
            }
            rmdir(self::CONF_DIR);
        }
    }

    /**
     * @param int $backTraceIndex
     * @return string
     */
    static private function getCallerFileName($backTraceIndex = 1)
    {
        $backtrace = debug_backtrace();
        if (isset($backtrace[$backTraceIndex]['file'])) {
            $filePath = $backtrace[$backTraceIndex]['file'];
        } else {
            $filePath = __FILE__;
        }

        return substr($filePath, 0, -strlen(pathinfo($filePath, PATHINFO_EXTENSION)));
    }

    /**
     * @return bool|string
     */
    static public function findExecutable()
    {
        $phpPath = getenv("TEST_PHP_EXECUTABLE");
        for ($i = 0; $i < 2; $i++) {
            $slashPosition = strrpos($phpPath, "/");
            if ($slashPosition) {
                $phpPath = substr($phpPath, 0, $slashPosition);
            } else {
                break;
            }
        }

        if ($phpPath && is_dir($phpPath)) {
            if (file_exists($phpPath."/fpm/php-fpm") && is_executable($phpPath."/fpm/php-fpm")) {
                /* gotcha */
                return $phpPath."/fpm/php-fpm";
            }
            $phpSbinFpmi = $phpPath."/sbin/php-fpm";
            if (file_exists($phpSbinFpmi) && is_executable($phpSbinFpmi)) {
                return $phpSbinFpmi;
            }
        }

        // try local php-fpm
        $fpmPath = dirname(__DIR__) . '/php-fpm';
        if (file_exists($fpmPath) && is_executable($fpmPath)) {
            return $fpmPath;
        }

        return false;
    }

    /**
     * Skip test if any of the supplied files does not exist.
     *
     * @param mixed $files
     */
    static public function skipIfAnyFileDoesNotExist($files)
    {
        if (!is_array($files)) {
            $files = array($files);
        }
        foreach ($files as $file) {
            if (!file_exists($file)) {
                die("skip File $file does not exist");
            }
        }
    }

    /**
     * Skip test if config file is invalid.
     *
     * @param string $configTemplate
     * @throws \Exception
     */
    static public function skipIfConfigFails(string $configTemplate)
    {
        $tester = new self($configTemplate, '', [], self::getCallerFileName());
        $testResult = $tester->testConfig();
        if ($testResult !== null) {
            self::clean(2);
            die("skip $testResult");
        }
    }

    /**
     * Skip test if IPv6 is not supported.
     */
    static public function skipIfIPv6IsNotSupported()
    {
        @stream_socket_client('tcp://[::1]:0', $errno);
        if ($errno != 111) {
            die('skip IPv6 is not supported.');
        }
    }

    /**
     * Skip if running on Travis.
     *
     * @param $message
     */
    static public function skipIfTravis($message)
    {
        if (getenv("TRAVIS")) {
            die('skip Travis: ' . $message);
        }
    }

    /**
     * Skip if not running as root.
     */
    static public function skipIfNotRoot()
    {
        if (getmyuid() != 0) {
            die('skip not running as root');
        }
    }

    /**
     * Skip if running as root.
     */
    static public function skipIfRoot()
    {
        if (getmyuid() == 0) {
            die('skip running as root');
        }
    }

    /**
     * Skip if posix extension not loaded.
     */
    static public function skipIfPosixNotLoaded()
    {
        if (!extension_loaded('posix')) {
            die('skip posix extension not loaded');
        }
    }

    /**
     * Tester constructor.
     *
     * @param string|array $configTemplate
     * @param string $code
     * @param array $options
     * @param string $fileName
     */
    public function __construct(
        $configTemplate,
        string $code = '',
        array $options = [],
        $fileName = null
    ) {
        $this->configTemplate = $configTemplate;
        $this->code = $code;
        $this->options = $options;
        $this->fileName = $fileName ?: self::getCallerFileName();
        $this->logTool = new LogTool();
        $this->debug = (bool) getenv('TEST_FPM_DEBUG');
    }

    /**
     * @param string $ini
     */
    public function setUserIni(string $ini)
    {
        $iniFile = __DIR__ . '/.user.ini';
        file_put_contents($iniFile, $ini);
    }

    /**
     * Test configuration file.
     *
     * @return null|string
     * @throws \Exception
     */
    public function testConfig()
    {
        $configFile = $this->createConfig();
        $cmd = self::findExecutable() . ' -t -y ' . $configFile . ' 2>&1';
        exec($cmd, $output, $code);
        if ($code) {
            return preg_replace("/\[.+?\]/", "", $output[0]);
        }

        return null;
    }

    /**
     * Start PHP-FPM master process
     *
     * @param array $extraArgs
     * @return bool
     * @throws \Exception
     */
    public function start(array $extraArgs = [])
    {
        $configFile = $this->createConfig();
        $desc = $this->outDesc ? [] : [1 => array('pipe', 'w'), 2 => array('redirect', 1)];
        $cmd = [self::findExecutable(), '-F', '-O', '-y', $configFile];
        if (getenv('TEST_FPM_RUN_AS_ROOT')) {
            $cmd[] = '--allow-to-run-as-root';
        }
        $cmd = array_merge($cmd, $extraArgs);

        $this->masterProcess = proc_open($cmd, $desc, $pipes);
        register_shutdown_function(
            function($masterProcess) use($configFile) {
                @unlink($configFile);
                if (is_resource($masterProcess)) {
                    @proc_terminate($masterProcess);
                    while (proc_get_status($masterProcess)['running']) {
                        usleep(10000);
                    }
                }
            },
            $this->masterProcess
        );
        if (!$this->outDesc !== false) {
            $this->outDesc = $pipes[1];
        }

        return true;
    }

    /**
     * Run until needle is found in the log.
     *
     * @param string $needle
     * @param int $max
     * @return bool
     * @throws \Exception
     */
    public function runTill(string $needle, $max = 10)
    {
        $this->start();
        $found = false;
        for ($i = 0; $i < $max; $i++) {
            $line = $this->getLogLine();
            if (is_null($line)) {
                break;
            }
            if (preg_match($needle, $line) === 1) {
                $found = true;
                break;
            }
        }
        $this->close(true);

        if (!$found) {
            return $this->error("The search pattern not found");
        }

        return true;
    }

    /**
     * Check if connection works.
     *
     * @param string $host
     * @param null|string $successMessage
     * @param null|string $errorMessage
     * @param int $attempts
     * @param int $delay
     */
    public function checkConnection(
        $host = '127.0.0.1',
        $successMessage = null,
        $errorMessage = 'Connection failed',
        $attempts = 20,
        $delay = 50000
    ) {
        $i = 0;
        do {
            if ($i > 0 && $delay > 0) {
                usleep($delay);
            }
            $fp = @fsockopen($host, $this->getPort());
        } while ((++$i < $attempts) && !$fp);

        if ($fp) {
            $this->message($successMessage);
            fclose($fp);
        } else {
            $this->message($errorMessage);
        }
    }


    /**
     * Execute request with parameters ordered for better checking.
     *
     * @param string $address
     * @param string|null $successMessage
     * @param string|null $errorMessage
     * @param string $uri
     * @param string $query
     * @param array $headers
     * @return Response
     */
    public function checkRequest(
        string $address,
        string $successMessage = null,
        string $errorMessage = null,
        $uri = '/ping',
        $query = '',
        $headers = []
    ) {
        return $this->request($query, $headers, $uri, $address, $successMessage, $errorMessage);
    }

    /**
     * Execute and check ping request.
     *
     * @param string $address
     * @param string $pingPath
     * @param string $pingResponse
     */
    public function ping(
        string $address = '{{ADDR}}',
        string $pingResponse = 'pong',
        string $pingPath = '/ping'
    ) {
        $response = $this->request('', [], $pingPath, $address);
        $response->expectBody($pingResponse, 'text/plain');
    }

    /**
     * Execute and check status request(s).
     *
     * @param array $expectedFields
     * @param string|null $address
     * @param string $statusPath
     * @param mixed $formats
     * @throws \Exception
     */
    public function status(
        array $expectedFields,
        string $address = null,
        string $statusPath = '/status',
        $formats = ['plain', 'html', 'xml', 'json', 'openmetrics']
    ) {
        if (!is_array($formats)) {
            $formats = [$formats];
        }

        require_once "status.inc";
        $status = new Status();
        foreach ($formats as $format) {
            $query = $format === 'plain' ? '' : $format;
            $response = $this->request($query, [], $statusPath, $address);
            $status->checkStatus($response, $expectedFields, $format);
        }
    }

    /**
     * Execute request.
     *
     * @param string $query
     * @param array $headers
     * @param string|null $uri
     * @param string|null $address
     * @param string|null $successMessage
     * @param string|null $errorMessage
     * @param bool $connKeepAlive
     * @return Response
     */
    public function request(
        string $query = '',
        array $headers = [],
        string $uri = null,
        string $address = null,
        string $successMessage = null,
        string $errorMessage = null,
        bool $connKeepAlive = false
    ) {
        if ($this->hasError()) {
            return new Response(null, true);
        }
        if (is_null($uri)) {
            $uri = $this->makeSourceFile();
        }

        $params = array_merge(
            [
                'GATEWAY_INTERFACE' => 'FastCGI/1.0',
                'REQUEST_METHOD'    => 'GET',
                'SCRIPT_FILENAME'   => $uri,
                'SCRIPT_NAME'       => $uri,
                'QUERY_STRING'      => $query,
                'REQUEST_URI'       => $uri . ($query ? '?'.$query : ""),
                'DOCUMENT_URI'      => $uri,
                'SERVER_SOFTWARE'   => 'php/fcgiclient',
                'REMOTE_ADDR'       => '127.0.0.1',
                'REMOTE_PORT'       => '7777',
                'SERVER_ADDR'       => '127.0.0.1',
                'SERVER_PORT'       => '80',
                'SERVER_NAME'       => php_uname('n'),
                'SERVER_PROTOCOL'   => 'HTTP/1.1',
                'DOCUMENT_ROOT'     => __DIR__,
                'CONTENT_TYPE'      => '',
                'CONTENT_LENGTH'    => 0
            ],
            $headers
        );
        $params = array_filter($params, function($value) {
            return !is_null($value);
        });

        try {
            $this->response = new Response(
                $this->getClient($address, $connKeepAlive)->request_data($params, false)
            );
            $this->message($successMessage);
        } catch (\Exception $exception) {
            if ($errorMessage === null) {
                $this->error("Request failed", $exception);
            } else {
                $this->message($errorMessage);
            }
            $this->response = new Response();
        }
        if ($this->debug) {
            $this->response->debugOutput();
        }
        return $this->response;
    }

    /**
     * Get client.
     *
     * @param string $address
     * @param bool $keepAlive
     * @return Client
     */
    private function getClient(string $address = null, $keepAlive = false)
    {
        $address = $address ? $this->processTemplate($address) : $this->getAddr();
        if ($address[0] === '/') { // uds
            $host = 'unix://' . $address;
            $port = -1;
        } elseif ($address[0] === '[') { // ipv6
            $addressParts = explode(']:', $address);
            $host = $addressParts[0];
            if (isset($addressParts[1])) {
                $host .= ']';
                $port = $addressParts[1];
            } else {
                $port = $this->getPort();
            }
        } else { // ipv4
            $addressParts = explode(':', $address);
            $host = $addressParts[0];
            $port = $addressParts[1] ?? $this->getPort();
        }

        if (!$keepAlive) {
            return new Client($host, $port);
        }

        if (!isset($this->clients[$host][$port])) {
            $client = new Client($host, $port);
            $client->setKeepAlive(true);
            $this->clients[$host][$port] = $client;
        }

        return $this->clients[$host][$port];
    }

    /**
     * Display logs
     *
     * @param int $number
     * @param string $ignore
     */
    public function displayLog(int $number = 1, string $ignore = 'systemd')
    {
        /* Read $number lines or until EOF */
        while ($number > 0 || ($number < 0 && !feof($this->outDesc))) {
            $a = fgets($this->outDesc);
            if (empty($ignore) || !strpos($a, $ignore)) {
                echo $a;
                $number--;
            }
        }
    }

    /**
     * Get a single log line
     *
     * @return null|string
     */
    private function getLogLine()
    {
        $read = [$this->outDesc];
        $write = null;
        $except = null;
        if (stream_select($read, $write, $except, $timeout=3)) {
            return fgets($this->outDesc);
        } else {
            return null;
        }
    }

    /**
     * Get log lines
     *
     * @param int $number
     * @param bool $skipBlank
     * @param string $ignore
     * @return array
     */
    public function getLogLines(int $number = 1, bool $skipBlank = false, string $ignore = 'systemd')
    {
        $lines = [];
        /* Read $n lines or until EOF */
        while ($number > 0 || ($number < 0 && !feof($this->outDesc))) {
            $line = $this->getLogLine();
            if (is_null($line)) {
                break;
            }
            if ((empty($ignore) || !strpos($line, $ignore)) && (!$skipBlank || strlen(trim($line)) > 0)) {
                $lines[] = $line;
                $number--;
            }
        }

        if ($this->debug) {
            foreach ($lines as $line) {
                echo "LOG LINE: " . $line;
            }
        }

        return $lines;
    }

    /**
     * @return mixed|string
     */
    public function getLastLogLine()
    {
        $lines = $this->getLogLines();

        return $lines[0] ?? '';
    }

    /**
     * @return string
     */
    public function getUser()
    {
        return get_current_user();
    }

    /**
     * @return string
     */
    public function getGroup()
    {
        return get_current_group();
    }

    /**
     * @return int
     */
    public function getUid()
    {
        return getmyuid();
    }

    /**
     * @return int
     */
    public function getGid()
    {
        return getmygid();
    }

    /**
     * Reload FPM by sending USR2 signal and optionally change config before that.
     *
     * @param string|array $configTemplate
     * @return string
     * @throws \Exception
     */
    public function reload($configTemplate = null)
    {
        if (!is_null($configTemplate)) {
            self::cleanConfigFiles();
            $this->configTemplate = $configTemplate;
            $this->createConfig();
        }

        return $this->signal('USR2');
    }

    /**
     * Send signal to the supplied PID or the server PID.
     *
     * @param string $signal
     * @param int|null $pid
     * @return string
     */
    public function signal($signal, int $pid = null)
    {
        if (is_null($pid)) {
            $pid = $this->getPid();
        }

        return exec("kill -$signal $pid");
    }

    /**
     * Terminate master process
     */
    public function terminate()
    {
        proc_terminate($this->masterProcess);
    }

    /**
     * Close all open descriptors and process resources
     *
     * @param bool $terminate
     */
    public function close($terminate = false)
    {
        if ($terminate) {
            $this->terminate();
        }
        fclose($this->outDesc);
        proc_close($this->masterProcess);
    }

    /**
     * Create a config file.
     *
     * @param string $extension
     * @return string
     * @throws \Exception
     */
    private function createConfig($extension = 'ini')
    {
        if (is_array($this->configTemplate)) {
            $configTemplates = $this->configTemplate;
            if (!isset($configTemplates['main'])) {
                throw new \Exception('The config template array has to have main config');
            }
            $mainTemplate = $configTemplates['main'];
            if (!is_dir(self::CONF_DIR)) {
                mkdir(self::CONF_DIR);
            }
            foreach ($this->createPoolConfigs($configTemplates) as $name => $poolConfig) {
                $this->makeFile(
                    'conf',
                    $this->processTemplate($poolConfig),
                    self::CONF_DIR,
                    $name
                );
            }
        } else {
            $mainTemplate = $this->configTemplate;
        }

        return $this->makeFile($extension, $this->processTemplate($mainTemplate));
    }

    /**
     * Create pool config templates.
     *
     * @param array $configTemplates
     * @return array
     * @throws \Exception
     */
    private function createPoolConfigs(array $configTemplates)
    {
        if (!isset($configTemplates['poolTemplate'])) {
            unset($configTemplates['main']);
            return $configTemplates;
        }
        $poolTemplate = $configTemplates['poolTemplate'];
        $configs = [];
        if (isset($configTemplates['count'])) {
            $start = $configTemplates['start'] ?? 1;
            for ($i = $start;  $i < $start + $configTemplates['count']; $i++) {
                $configs[$i] = str_replace('%index%', $i, $poolTemplate);
            }
        } elseif (isset($configTemplates['names'])) {
            foreach($configTemplates['names'] as $name) {
                $configs[$name] = str_replace('%name%', $name, $poolTemplate);
            }
        } else {
            throw new \Exception('The config template requires count or names if poolTemplate set');
        }
        return $configs;
    }

    /**
     * Process template string.
     *
     * @param string $template
     * @return string
     */
    private function processTemplate(string $template)
    {
        $vars = [
            'FILE:LOG:ACC' => ['getAbsoluteFile', self::FILE_EXT_LOG_ACC],
            'FILE:LOG:ERR' => ['getAbsoluteFile', self::FILE_EXT_LOG_ERR],
            'FILE:LOG:SLOW' => ['getAbsoluteFile', self::FILE_EXT_LOG_SLOW],
            'FILE:PID' => ['getAbsoluteFile', self::FILE_EXT_PID],
            'RFILE:LOG:ACC' => ['getRelativeFile', self::FILE_EXT_LOG_ACC],
            'RFILE:LOG:ERR' => ['getRelativeFile', self::FILE_EXT_LOG_ERR],
            'RFILE:LOG:SLOW' => ['getRelativeFile', self::FILE_EXT_LOG_SLOW],
            'RFILE:PID' => ['getRelativeFile', self::FILE_EXT_PID],
            'ADDR:IPv4' => ['getAddr', 'ipv4'],
            'ADDR:IPv4:ANY' => ['getAddr', 'ipv4-any'],
            'ADDR:IPv6' => ['getAddr', 'ipv6'],
            'ADDR:IPv6:ANY' => ['getAddr', 'ipv6-any'],
            'ADDR:UDS' => ['getAddr', 'uds'],
            'PORT' => ['getPort', 'ip'],
            'INCLUDE:CONF' => self::CONF_DIR . '/*.conf',
            'USER' => ['getUser'],
            'GROUP' => ['getGroup'],
            'UID' => ['getUid'],
            'GID' => ['getGid'],
        ];
        $aliases = [
            'ADDR' => 'ADDR:IPv4',
            'FILE:LOG' => 'FILE:LOG:ERR',
        ];
        foreach ($aliases as $aliasName => $aliasValue) {
            $vars[$aliasName] = $vars[$aliasValue];
        }

        return preg_replace_callback(
            '/{{([a-zA-Z0-9:]+)(\[\w+\])?}}/',
            function ($matches) use ($vars) {
                $varName = $matches[1];
                if (!isset($vars[$varName])) {
                    $this->error("Invalid config variable $varName");
                    return 'INVALID';
                }
                $pool = $matches[2] ?? 'default';
                $varValue = $vars[$varName];
                if (is_string($varValue)) {
                    return $varValue;
                }
                $functionName = array_shift($varValue);
                $varValue[] = $pool;
                return call_user_func_array([$this, $functionName], $varValue);
            },
            $template
        );
    }

    /**
     * @param string $type
     * @param string $pool
     * @return string
     */
    public function getAddr(string $type = 'ipv4', $pool = 'default')
    {
        $port = $this->getPort($type, $pool, true);
        if ($type === 'uds') {
            $address = $this->getFile($port . '.sock');

            // Socket max path length is 108 on Linux and 104 on BSD,
            // so we use the latter
            if (strlen($address) <= 104) {
                return $address;
            }

            return sys_get_temp_dir().'/'.
                hash('crc32', dirname($address)).'-'.
                basename($address);
        }

        return $this->getHost($type) . ':' . $port;
    }

    /**
     * @param string $type
     * @param string $pool
     * @param bool $useAsId
     * @return int
     */
    public function getPort(string $type = 'ip', $pool = 'default', $useAsId = false)
    {
        if ($type === 'uds' && !$useAsId) {
            return -1;
        }

        if (isset($this->ports['values'][$pool])) {
            return $this->ports['values'][$pool];
        }
        $port = ($this->ports['last'] ?? 9000 + PHP_INT_SIZE - 1) + 1;
        $this->ports['values'][$pool] = $this->ports['last'] = $port;

        return $port;
    }

    /**
     * @param string $type
     * @return string
     */
    public function getHost(string $type = 'ipv4')
    {
        switch ($type) {
            case 'ipv6-any':
                return '[::]';
            case 'ipv6':
                return '[::1]';
            case 'ipv4-any':
                return '0.0.0.0';
            default:
                return '127.0.0.1';
        }
    }

    /**
     * Get listen address.
     *
     * @param string|null $template
     * @return string
     */
    public function getListen($template = null)
    {
        return $template ? $this->processTemplate($template) : $this->getAddr();
    }

    /**
     * Get PID.
     *
     * @return int
     */
    public function getPid()
    {
        $pidFile = $this->getFile('pid');
        if (!is_file($pidFile)) {
            return (int) $this->error("PID file has not been created");
        }
        $pidContent = file_get_contents($pidFile);
        if (!is_numeric($pidContent)) {
            return (int) $this->error("PID content '$pidContent' is not integer");
        }

        return (int) $pidContent;
    }


    /**
     * @param string $extension
     * @param string|null $dir
     * @param string|null $name
     * @return string
     */
    private function getFile(string $extension, $dir = null, $name = null)
    {
        $fileName = (is_null($name) ? $this->fileName : $name . '.') . $extension;

        return is_null($dir) ? $fileName : $dir . '/'  . $fileName;
    }

    /**
     * @param string $extension
     * @return string
     */
    private function getAbsoluteFile(string $extension)
    {
        return $this->getFile($extension);
    }

    /**
     * @param string $extension
     * @return string
     */
    private function getRelativeFile(string $extension)
    {
        $fileName = rtrim(basename($this->fileName), '.');

        return $this->getFile($extension, null, $fileName);
    }

    /**
     * @param string $extension
     * @param string $prefix
     * @return string
     */
    private function getPrefixedFile(string $extension, string $prefix = null)
    {
        $fileName = rtrim($this->fileName, '.');
        if (!is_null($prefix)) {
            $fileName = $prefix . '/' . basename($fileName);
        }

        return $this->getFile($extension, null, $fileName);
    }

    /**
     * @param string $extension
     * @param string $content
     * @param string|null $dir
     * @param string|null $name
     * @return string
     */
    private function makeFile(string $extension, string $content = '', $dir = null, $name = null)
    {
        $filePath = $this->getFile($extension, $dir, $name);
        file_put_contents($filePath, $content);

        return $filePath;
    }

    /**
     * @return string
     */
    public function makeSourceFile()
    {
        return $this->makeFile('src.php', $this->code);
    }

    /**
     * @param string|null $msg
     */
    private function message($msg)
    {
        if ($msg !== null) {
            echo "$msg\n";
        }
    }

    /**
     * @param string $msg
     * @param \Exception|null $exception
     */
    private function error($msg, \Exception $exception = null)
    {
        $this->error =  'ERROR: ' . $msg;
        if ($exception) {
            $this->error .= '; EXCEPTION: ' . $exception->getMessage();
        }
        $this->error .= "\n";

        echo $this->error;
    }

    /**
     * @return bool
     */
    private function hasError()
    {
        return !is_null($this->error) || !is_null($this->logTool->getError());
    }

    /**
     * Expect file with a supplied extension to exist.
     *
     * @param string $extension
     * @param string $prefix
     * @return bool
     */
    public function expectFile(string $extension, $prefix = null)
    {
        $filePath = $this->getPrefixedFile($extension, $prefix);
        if (!file_exists($filePath)) {
            return $this->error("The file $filePath does not exist");
        }

        return true;
    }

    /**
     * Expect file with a supplied extension to not exist.
     *
     * @param string $extension
     * @param string $prefix
     * @return bool
     */
    public function expectNoFile(string $extension, $prefix = null)
    {
        $filePath = $this->getPrefixedFile($extension, $prefix);
        if (file_exists($filePath)) {
            return $this->error("The file $filePath exists");
        }

        return true;
    }

    /**
     * Expect message to be written to FastCGI error stream.
     *
     * @param string $message
     * @param int $limit
     * @param int $repeat
     */
    public function expectFastCGIErrorMessage(
        string $message,
        int $limit = 1024,
        int $repeat = 0
    ) {
        $this->logTool->setExpectedMessage($message, $limit, $repeat);
        $this->logTool->checkTruncatedMessage($this->response->getErrorData());
    }

    /**
     * Expect reloading lines to be logged.
     *
     * @param int $socketCount
     */
    public function expectLogReloadingNotices($socketCount = 1)
    {
        $this->logTool->expectReloadingLines($this->getLogLines($socketCount + 4));
    }

    /**
     * Expect starting lines to be logged.
     */
    public function expectLogStartNotices()
    {
        $this->logTool->expectStartingLines($this->getLogLines(2));
    }

    /**
     * Expect terminating lines to be logged.
     */
    public function expectLogTerminatingNotices()
    {
        $this->logTool->expectTerminatorLines($this->getLogLines(-1));
    }

    /**
     * Expect log message that can span multiple lines.
     *
     * @param string $message
     * @param int $limit
     * @param int $repeat
     * @param bool $decorated
     * @param bool $wrapped
     */
    public function expectLogMessage(
        string $message,
        int $limit = 1024,
        int $repeat = 0,
        bool $decorated = true,
        bool $wrapped = true
    ) {
        $this->logTool->setExpectedMessage($message, $limit, $repeat);
        if ($wrapped) {
            $logLines = $this->getLogLines(-1, true);
            $this->logTool->checkWrappedMessage($logLines, true, $decorated);
        } else {
            $logLines = $this->getLogLines(1, true);
            $this->logTool->checkTruncatedMessage($logLines[0] ?? '');
        }
        if ($this->debug) {
            $this->message("-------------- LOG LINES: -------------");
            var_dump($logLines);
            $this->message("---------------------------------------\n");
        }
    }

    /**
     * Expect a single log line.
     *
     * @param string $message
     * @return bool
     */
    public function expectLogLine(string $message, bool $is_stderr = true)
    {
        $messageLen = strlen($message);
        $limit = $messageLen > 1024 ? $messageLen + 16 : 1024;
        $this->logTool->setExpectedMessage($message, $limit);
        $logLines = $this->getLogLines(1, true);
        if ($this->debug) {
            $this->message("LOG LINE: " . ($logLines[0] ?? ''));
        }

        return $this->logTool->checkWrappedMessage($logLines, false, true, $is_stderr);
    }

    /**
     * Expect log entry.
     *
     * @param string $type The log type
     * @param string $message The expected message
     * @param string|null $pool The pool for pool prefixed log entry
     * @param int $count The number of items
     * @return bool
     */
    private function expectLogEntry(string $type, string $message, $pool = null, $count = 1)
    {
        for ($i = 0; $i < $count; $i++) {
            if (!$this->logTool->expectEntry($type, $this->getLastLogLine(), $message, $pool)) {
                return false;
            }
        }
        return true;
    }

    /**
     * Expect a log debug message.
     *
     * @param string $message
     * @param string|null $pool
     * @param int $count
     * @return bool
     */
    public function expectLogDebug(string $message, $pool = null, $count = 1)
    {
        return $this->expectLogEntry(LogTool::DEBUG, $message, $pool, $count);
    }

    /**
     * Expect a log notice.
     *
     * @param string $message
     * @param string|null $pool
     * @param int $count
     * @return bool
     */
    public function expectLogNotice(string $message, $pool = null, $count = 1)
    {
        return $this->expectLogEntry(LogTool::NOTICE, $message, $pool, $count);
    }

    /**
     * Expect a log warning.
     *
     * @param string $message
     * @param string|null $pool
     * @param int $count
     * @return bool
     */
    public function expectLogWarning(string $message, $pool = null, $count = 1)
    {
        return $this->expectLogEntry(LogTool::WARNING, $message, $pool, $count);
    }

    /**
     * Expect a log error.
     *
     * @param string $message
     * @param string|null $pool
     * @param int $count
     * @return bool
     */
    public function expectLogError(string $message, $pool = null, $count = 1)
    {
        return $this->expectLogEntry(LogTool::ERROR, $message, $pool, $count);
    }

    /**
     * Expect a log alert.
     *
     * @param string $message
     * @param string|null $pool
     * @param int $count
     * @return bool
     */
    public function expectLogAlert(string $message, $pool = null, $count = 1)
    {
        return $this->expectLogEntry(LogTool::ALERT, $message, $pool, $count);
    }

    /**
     * Expect no log lines to be logged.
     *
     * @return bool
     */
    public function expectNoLogMessages()
    {
        $logLines = $this->getLogLines(-1, true);
        if (!empty($logLines)) {
            return $this->error(
                "Expected no log lines but following lines logged:\n" . implode("\n", $logLines)
            );
        }

        return true;
    }

    /**
     * Print content of access log.
     */
    public function printAccessLog()
    {
        $accessLog = $this->getFile('acc.log');
        if (is_file($accessLog)) {
            print file_get_contents($accessLog);
        }
    }
}