-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path_ping.php
More file actions
1560 lines (1347 loc) · 35.6 KB
/
_ping.php
File metadata and controls
1560 lines (1347 loc) · 35.6 KB
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
<?php
/**
* @file
* The Ping Utility.
*
* FILE IS SUPPOSED TO BE IN DRUPAL ROOT DIRECTORY (NEXT TO INDEX.PHP) !!
*/
declare(strict_types=1);
use Drupal\Core\Database\Database;
use Drupal\Core\DrupalKernel;
use Drupal\Core\Site\Settings;
use Symfony\Component\HttpFoundation\Request;
if (empty(getenv('TESTING'))) {
$app = new App();
$app->run();
// Exit immediately.
// Note the shutdown function registered at the beginning.
exit();
}
/**
* The Application itself.
*/
// @codingStandardsIgnoreLine Drupal.Classes.ClassFileName.NoMatch
class App {
/**
* Profile object.
*
* @var object
*/
private $profile;
/**
* Status object.
*
* @var object
*/
private $status;
/**
* The main function.
*/
public function run(): void {
/*
* Setup
*/
// Start output buffering as any PHP notice would return 503 error code
// if printed before setting headers.
ob_start();
// Start profiling as early as possible.
$this->profile = new Profile();
$this->status = new Status();
$this->setupShutdown();
$this->disableNewrelic();
// Will be corrected later when not failing.
$this->setHeader(503);
/*
* Actual stuff.
*/
$check = $this->check('BootstrapChecker');
$settings = $check->getSettings();
$check = $this->check('DbChecker');
$servers = MemcacheChecker::connectionsFromSettings($settings);
$check = $this->check('MemcacheChecker', [$servers]);
[$host, $port] = RedisChecker::connectionsFromSettings($settings);
$check = $this->check('RedisChecker', [$host, $port]);
$connections = ElasticsearchChecker::connectionsFromSettings($settings);
$check = $this->check('ElasticsearchChecker', [$connections]);
$check = $this->check('FsSchemeCreateChecker');
$file = $check->getFile();
$check = $this->check('FsSchemeDeleteChecker', [$file]);
$check = $this->check('FsSchemeCleanupChecker');
$check = $this->check('CustomPingChecker');
/*
* Finish.
*/
$this->profile->stop();
$slows = $this->profile->getByDuration(1000, NULL);
$payloads = $this->profile2logs($slows, 'slow');
$this->logErrors($payloads, 'notice');
$payloads = $this->status->getBySeverity('warning');
$payloads = $this->status2logs($payloads, 'warning');
$this->logErrors($payloads, 'warning');
$payloads = $this->status->getBySeverity('error');
$payloads = $this->status2logs($payloads, 'error');
$this->logErrors($payloads, 'error');
// Stop buffering before setting headers. After that it doesn't matter
// if there's any output as script is not going to give 503 error code
// anymore.
$buffered_output = ob_get_clean();
if (!empty($payloads)) {
$code = 500;
$msg = 'INTERNAL ERROR';
}
else {
$code = 200;
$msg = 'CONGRATULATIONS';
}
$this->setHeader($code);
// Split up this message, to prevent the remote chance
// of monitoring software reading the source code
// if mod_php fails and then matching the string.
print "$msg $code" . PHP_EOL;
$token = $this->getToken($settings);
if (!$this->isDebug($token) && !$this->isCli()) {
return;
}
if ($this->isCli()) {
print <<<TXT
<p>Debug token: $token</p>
TXT;
}
$status_tbl = $this->status->getTextTable(PHP_EOL);
$profiling_tbl = $this->profile->getTextTable(PHP_EOL);
print <<<TXT
<pre style="color:red">
$buffered_output
</pre>
<pre>
$status_tbl
</pre>
<pre>
$profiling_tbl
</pre>
TXT;
}
/**
* Custom shutdown.
*
* Register our shutdown function so that no other shutdown functions run
* before this one. This shutdown function calls exit(), immediately
* short-circuiting any other shutdown functions, such as those registered by
* the devel.module for statistics.
*/
public function setupShutdown(): void {
// @codingStandardsIgnoreLine PHPCS_SecurityAudit.BadFunctions.FunctionHandlingFunctions.WarnFunctionHandling
register_shutdown_function(function () {
exit();
});
}
/**
* Perform the check.
*
* @param string $class
* The checker class.
* @param array $args
* The args for checker constructor.
*
* @return object
* Return the checker object.
*/
public function check(string $class, array $args = []): object {
$checker = new $class(...$args);
$this->profile->measure([$checker, 'check'], $checker->getName());
[$status, $payload] = $checker->getStatusInfo();
$name = $checker->getName();
$this->status->set($name, $status, $payload);
return $checker;
}
/**
* Disable NewRelic.
*
* We want to ignore _ping.php from New Relic statistics.
* _ping.php skews the overall statistics significantly.
*/
public function disableNewrelic(): void {
if (extension_loaded('newrelic')) {
newrelic_ignore_transaction();
}
}
/**
* Set response header.
*
* It can be called multiple times.
* Originally the error status can be set.
* But if the code finishes without errors,
* then we can override that with successful status.
*
* @param int $code
* The status code, for ex 200, 404, etc.
*
* @return string
* The status message string.
*/
public function setHeader(int $code): string {
$map = [
200 => 'OK',
500 => 'Internal Server Error',
503 => 'Service Unavailable',
];
$msg = $map[$code];
$header = sprintf('HTTP/1.1 %d %s', $code, $msg);
header($header);
return $msg;
}
/**
* Convert Status array for logging.
*
* @param array $payloads
* List of payloads.
* @param string $status
* Set status for all payloads.
*
* @return array
* Return upgraded payload array.
*/
public function status2logs(array $payloads, string $status): array {
$payloads2 = [];
foreach ($payloads as $check => $payload) {
$payloads2[] = array_merge([
'check' => $check,
'status' => $status,
], $payload);
}
return $payloads2;
}
/**
* Log all slow requests.
*
* Fetch all slow requests from the profiling system,
* and log them.
*
* @param array $slows
* Slow array.
* @param string $status
* The status to assign.
*
* @return array
* Return array of slow messages.
*/
public function profile2logs(array $slows, string $status): array {
$payloads = [];
foreach ($slows as $check => $duration) {
$payloads[] = [
'check' => $check,
'status' => $status,
'duration' => $duration,
'unit' => 'ms',
];
}
return $payloads;
}
/**
* Log errors according to the environment.
*
* We recognize following envs:
* - drupal -> Drupal logger.
* - silta -> stderr.
* - lando -> stderr.
* - the rest -> syslog().
*
* @param array $payloads
* Array of payload arrays, containing error message and additional info.
* @param string $severity
* The severity of Drupal logger (method name).
*/
public function logErrors(array $payloads, string $severity): void {
if (!empty(getenv('TESTING'))) {
$logger = function (string $msg) {
global $_logs;
if (empty($_logs)) {
$_logs = [];
}
$_logs[] = $msg;
};
}
elseif (method_exists('\Drupal', 'logger')) {
$logger = function (string $msg) use ($severity) {
try {
// Replace curly braces with double parentheses because Drupal logging
// is unable to handle JSON.
$msg = str_replace(['{', '}'], ['((', '))'], $msg);
\Drupal::logger('drupal_ping')->{$severity}($msg);
}
catch (\Exception $e) {
}
};
}
elseif (!empty(getenv('SILTA_CLUSTER')) || !empty(getenv('LANDO'))) {
$logger = function (string $msg) {
error_log("ping: $msg");
};
}
else {
$logger = function (string $msg) {
syslog(LOG_ERR | LOG_LOCAL6, "ping: $msg");
};
}
foreach ($payloads as $payload) {
$payload = json_encode($payload);
$logger($payload);
}
}
/**
* Provide Debug Access Token.
*
* This is needed to limit access to debug info over the web.
* Many methods are tried in sequence to define the code.
*
* @param array $settings
* The Drupal settings.
*
* @return string
* Access token.
*/
public function getToken(array $settings): string {
// $settings['ping_token'].
if (!empty($settings['ping_token'])) {
$token = $settings['ping_token'];
return $token;
}
// Env(PING_TOKEN).
if (!empty(getenv('PING_TOKEN'))) {
$token = (string) getenv('PING_TOKEN');
return $token;
}
// Md5(Concatenated-values-of-some-env-variables).
$token = [];
$env = getenv();
ksort($env);
foreach ($env as $key => $value) {
if (preg_match('/^(DB|ENVIRONMENT_NAME|PROJECT_NAME|S+MTP|VARNISH|WARDEN)/', $key)) {
// Remove newlines and other whitespace,
// because the interpretation differs from shell to web.
$value = preg_replace('/\s/', '', $value);
$token[] = $value;
}
}
if (!empty($token)) {
$token = implode('-', $token);
$token = md5($token);
return $token;
}
// Md5($settings['hash_salt']).
if (!empty($settings['hash_salt'])) {
$token = md5($settings['hash_salt']);
return $token;
}
// Md5(Hostname).
$token = gethostname();
$token = md5($token);
return $token;
}
/**
* Detect if we are running in CLI mode.
*
* @return bool
* True = CLI mode, False = WEB mode.
*/
public function isCli(): bool {
$isCli = php_sapi_name() === 'cli';
return $isCli;
}
/**
* Detect if debug information should be provided on request.
*
* Currently it is matching '?debug=token'
*
* @param string $token
* The token to be checked if present in the request.
*
* @return bool
* Return if we need to emit debugging info.
*/
public function isDebug(string $token): bool {
// @codingStandardsIgnoreLine DrupalPractice.Variables.GetRequestData.SuperglobalAccessedWithVar
$debug = $_GET['debug'] ?? NULL;
if (empty($debug)) {
return FALSE;
}
return $debug == $token;
}
}
/*
* Actual functionality (to be profiled).
*/
/**
* Abstract Checker class.
*/
// @codingStandardsIgnoreLine Drupal.Classes.ClassFileName.NoMatch
abstract class Checker {
/**
* The status for the check result.
*
* @var string
*/
protected $status = '';
/**
* The name of the checker.
*
* @var string
*/
protected $name = '';
/**
* The payload of the message.
*
* @var array
*/
protected $payload = [];
/*
* Configure the checker.
* abstract public function __construct(...config...);
*/
/**
* Get human-readable checker name.
*
* @return string
* Return human-readable checker name.
*/
public function getName(): string {
return $this->name;
}
/**
* Return checker status.
*
* @return array
* Array of [
* (string) $status ('success'|'disabled'|'error'|'warning'),
* (array) $payload (related details)
* ]
*/
public function getStatusInfo(): array {
return [
$this->status,
$this->payload,
];
}
/**
* Safety wrapper for the check function.
*
* The purpose of this function is to catch exceptions.
*
* @param string $status
* Status: 'disabled', 'success', 'warning', 'error'.
* @param string $message
* The message of the status.
* @param array $payload
* Additional details.
*/
protected function setStatus(string $status, string $message = '', array $payload = []): void {
$this->status = $status;
$p = [];
if (!empty($message)) {
$p = array_merge($p, ['message' => $message]);
}
if (!empty($payload)) {
$p = array_merge($p, $payload);
}
$this->payload = $p;
}
/**
* Safety wrapper for the check function.
*
* The purpose of this function is to catch exceptions.
*/
public function check(): void {
$this->setStatus('success');
try {
$this->check2();
}
catch (\Exception $e) {
$this->setStatus('error', 'Internal error.', [
'function' => sprintf('%s::check2()', get_class($this)),
'exception' => $e->getMessage(),
]);
}
}
/**
* The function that is going to do the actual check.
*
* The implementation should use setStatus().
* The if not used, the status will be 'success'.
*/
abstract protected function check2(): void;
}
/**
* Check Drupal Bootstrap.
*/
// @codingStandardsIgnoreLine Drupal.Classes.ClassFileName.NoMatch
class BootstrapChecker extends Checker {
/**
* The name of the checker.
*
* @var string
*/
protected $name = 'bootstrap';
/**
* Drupal Settings.
*
* @var array
*/
protected $settings;
/**
* Get Drupal Settings.
*
* @return array
* The Drupal settings.
*/
public function getSettings(): array {
return empty($this->settings) ? [] : $this->settings;
}
/**
* Drupal bootstrap.
*
* This is a prerequisite for the rest of the checks.
* It is a check, but also a setup.
*/
protected function check2(): void {
/**
* @psalm-suppress MissingFile
*/
$autoloader = require_once 'autoload.php';
$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
// Define DRUPAL_ROOT if it's not yet defined by bootstrap.
if (!defined('DRUPAL_ROOT')) {
define('DRUPAL_ROOT', getcwd());
}
// Get current settings.
// And save them for other functions.
$this->settings = Settings::getAll();
// Define file_uri_scheme if it does not exist, it's required by realpath().
// The function file_uri_scheme is deprecated and will be removed in 9.0.0.
if (!function_exists('file_uri_scheme')) {
/**
* Hmm.
*/
// @codingStandardsIgnoreLine Drupal.NamingConventions.ValidFunctionName.NotCamelCaps
function file_uri_scheme($uri) { // @phpstan-ignore-line
return \Drupal::service('file_system')->uriScheme($uri);
}
}
}
}
/**
* Check Drupal Dababase availability.
*/
// @codingStandardsIgnoreLine Drupal.Classes.ClassFileName.NoMatch
class DbChecker extends Checker {
/**
* The name of the checker.
*
* @var string
*/
protected $name = 'db';
/**
* Check: Main database connectivity.
*/
protected function check2(): void {
// Check that the main database is active.
$result = Database::getConnection()
->query('SELECT * FROM {users} WHERE uid = 1')
->fetchAllKeyed();
$count = count($result);
$expected = 1;
if ($count == $expected) {
return;
}
else {
$this->setStatus('error', 'Master database returned invalid results.', [
'actual_count' => $count,
'expected_count' => $expected,
]);
return;
}
}
}
/**
* Check Memcache connectivity.
*/
// @codingStandardsIgnoreLine Drupal.Classes.ClassFileName.NoMatch
class MemcacheChecker extends Checker {
/**
* The name of the checker.
*
* @var string
*/
protected $name = 'memcache';
/**
* The list of servers to be checked.
*
* @var array
*/
protected $servers;
/**
* Set configuration.
*
* @param array $servers
* List of servers.
*/
public function __construct(array $servers = NULL) {
$this->servers = $servers;
}
/**
* Convert settings to usable data for this checker.
*
* @param array $settings
* The Drupal settings array.
*
* @return array
* Return array of format [['host' => (string)$hostname,
* 'port' => (int)$portnr, 'bin' => (string)$bin]].
*/
public static function connectionsFromSettings(array $settings): array {
$servers = $settings['memcache']['servers'] ?? [];
$servers2 = [];
foreach ($servers as $address => $bin) {
[$host, $port] = explode(':', $address);
$servers2[] = [
'host' => $host,
'port' => (int) $port,
'bin' => $bin,
];
}
return $servers2;
}
/**
* Check: Memcache connectivity.
*
* Verify that all memcache instances are running on this server.
* There are 3 statuses:
* - 'success' - all instances are available.
* - 'warning' - 0<x<all instances are not available.
* - 'error' - all instances are unavailable.
*/
protected function check2(): void {
if (empty($this->servers)) {
$this->setStatus('disabled');
return;
}
$good_count = 0;
$bad_count = 0;
$msgs = [];
// Loop through the defined servers.
foreach ($this->servers as $s) {
// We are not relying on Memcache or Memcached classes.
// For speed and simplicity we use just basic networking.
$socket = @fsockopen($s['host'], $s['port'], $errno, $errstr, 1);
if (!empty($errstr)) {
$msgs[] = [
'host' => $s['host'],
'port' => $s['port'],
'error' => $errstr,
];
$bad_count++;
continue;
}
// @codingStandardsIgnoreLine PHPCS_SecurityAudit.BadFunctions.FilesystemFunctions.WarnFilesystem
fwrite($socket, "stats\n");
// Just check the first line of the reponse.
// @codingStandardsIgnoreLine PHPCS_SecurityAudit.BadFunctions.FilesystemFunctions.WarnFilesystem
$line = fgets($socket);
if (!preg_match('/^STAT /', $line)) {
$msgs[] = [
'host' => $s['host'],
'port' => $s['port'],
'message' => 'Unexpected response.',
'response' => $line,
];
$bad_count++;
continue;
}
// @codingStandardsIgnoreLine PHPCS_SecurityAudit.BadFunctions.FilesystemFunctions.WarnFilesystem
fclose($socket);
$good_count++;
}
if ($good_count > 0 && $bad_count < 1) {
return;
}
if ($good_count > 0 && $bad_count > 0) {
$this->setStatus('warning', 'Connection warnings.', ['warnings' => $msgs]);
return;
}
if ($good_count < 1 && $bad_count > 0) {
$this->setStatus('warning', 'Connection errors.', ['errors' => $msgs]);
return;
}
$this->setStatus('error', 'Internal error.');
}
}
/**
* Check Redis connectivity.
*/
// @codingStandardsIgnoreLine Drupal.Classes.ClassFileName.NoMatch
class RedisChecker extends Checker {
/**
* The name of the checker.
*
* @var string
*/
protected $name = 'redis';
/**
* Hostname.
*
* @var string
*/
protected $host;
/**
* Port.
*
* @var int
*/
protected $port;
/**
* Set configuration.
*
* @param string $host
* Hostname.
* @param int $port
* Port.
*/
public function __construct(string $host = NULL, int $port = NULL) {
$this->host = $host;
$this->port = $port;
}
/**
* Convert settings to usable data for this checker.
*
* @param array $settings
* The Drupal settings array.
*
* @return array
* Return array of format [(string) $host, (int) $port].
*/
public static function connectionsFromSettings(array $settings): array {
$host = $settings['redis.connection']['host'] ?? NULL;
$port = empty($settings['redis.connection']['port']) ? NULL : (int) $settings['redis.connection']['port'];
return [$host, $port];
}
/**
* Check: Redis connectivity.
*
* Handles both:
* - TCP/IP - both host and port are defined.
* - Unix Socket - only host is defined as path.
*/
protected function check2(): void {
if (empty($this->host) && empty($this->port)) {
$this->setStatus('disabled');
return;
}
/*
* In case of a socket,
* only host is defined.
*/
// Use PhpRedis, PRedis is outdated.
$redis = new \Redis();
if ($redis->connect($this->host, $this->port)) {
return;
}
else {
$this->setStatus('error', 'Unable to connect.', [
'host' => $this->host,
'port' => $this->port,
]);
return;
}
}
}
/**
* Check ElasticSearch connectivity.
*/
// @codingStandardsIgnoreLine Drupal.Classes.ClassFileName.NoMatch
class ElasticsearchChecker extends Checker {
/**
* The name of the checker.
*
* @var string
*/
protected $name = 'elasticsearch';
/**
* Connections to be checked.
*
* @var array
*/
protected $connections;
/**
* Set configuration.
*
* @param array $connections
* Connections from connectionsFromSettings().
*/
public function __construct(array $connections = NULL) {
$this->connections = $connections;
}
/**
* Convert settings to usable data for this checker.
*
* We use ping-specific configuration to check Elasticsearch.
* Because there are way too many ways how Elasticsearch
* connections can be defined depending on libs/mods/versions.
*
* @param array $settings
* The Drupal settings array.
*
* @return array
* Return connections array extracted from settings,
* possibly reformatted.
*/
public static function connectionsFromSettings(array $settings): array {
$connections = $settings['ping_elasticsearch_connections'] ?? [];
return $connections;
}
/**
* Check: Elasticsearch connectivity by curl.
*/
protected function check2(): void {
if (empty($this->connections)) {
$this->setStatus('disabled');
return;
}
$warnings = [];
$errors = [];
// Loop through Elasticsearch connections.
// Perform basic curl request,
// and ensure we get green status back.
foreach ($this->connections as $c) {
switch ($c['severity']) {
case 'warning':
// @codingStandardsIgnoreLine DrupalPractice.CodeAnalysis.VariableAnalysis.UnusedVariable
$msgs = &$warnings;
break;
case 'error':
// @codingStandardsIgnoreLine DrupalPractice.CodeAnalysis.VariableAnalysis.UnusedVariable
$msgs = &$errors;
break;
}
$url = sprintf('%s://%s:%d%s', $c['proto'], $c['host'], $c['port'], '/_cluster/health');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 2000);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 2000);
curl_setopt($ch, CURLOPT_USERAGENT, "ping");
// @codingStandardsIgnoreLine PHPCS_SecurityAudit.BadFunctions.FilesystemFunctions.WarnFilesystem
$json = curl_exec($ch);
if (empty($json)) {
$msgs[] = [
'url' => $url,
'errno' => curl_errno($ch),
'errstr' => curl_error($ch),
];
curl_close($ch);
continue;
}
curl_close($ch);
$data = json_decode($json);
if (empty($data)) {
$msgs[] = [
'url' => $url,
'message' => 'Unable to decode JSON response',
];
continue;
}
if (empty($data->status)) {
$msgs[] = [
'url' => $url,
'message' => 'Response does not contain status',
];
continue;
}
if ($data->status !== 'green') {
$msgs[] = [
'url' => $url,
'status' => $data->status,
'message' => 'Not green',
];
continue;