-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCheckCommand.php
More file actions
823 lines (726 loc) · 24.2 KB
/
CheckCommand.php
File metadata and controls
823 lines (726 loc) · 24.2 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
<?php
declare(strict_types=1);
namespace OpenForgeProject\MageForge\Console\Command\System;
use Composer\Semver\Comparator;
use Magento\Framework\App\ProductMetadataInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Console\Cli;
use Magento\Framework\Escaper;
use Magento\Framework\HTTP\ClientFactory;
use Magento\Framework\Shell;
use OpenForgeProject\MageForge\Console\Command\AbstractCommand;
use Symfony\Component\Console\Helper\TableSeparator;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Command for checking system information
*/
class CheckCommand extends AbstractCommand
{
private const NODE_LTS_URL = 'https://nodejs.org/dist/index.json';
/**
* @param ProductMetadataInterface $productMetadata
* @param Escaper $escaper
* @param ResourceConnection $resourceConnection
* @param ClientFactory $httpClientFactory
* @param Shell $shell
*/
public function __construct(
private readonly ProductMetadataInterface $productMetadata,
private readonly Escaper $escaper,
private readonly ResourceConnection $resourceConnection,
private readonly ClientFactory $httpClientFactory,
private readonly Shell $shell,
) {
parent::__construct();
}
/**
* Configure command.
*
* @return void
*/
protected function configure(): void
{
$this
->setName($this->getCommandName('system', 'check'))
->setDescription('Displays system information like PHP version and Node.js version')
->setAliases(['system:check']);
}
/**
* Execute command.
*
* @param InputInterface $input
* @param OutputInterface $output
* @return int
*/
protected function executeCommand(InputInterface $input, OutputInterface $output): int
{
$phpVersion = phpversion();
$nodeVersion = $this->getNodeVersion();
$mysqlVersion = $this->getShortMysqlVersion();
$dbType = $this->getDatabaseType();
$osInfo = $this->getShortOsInfo();
$magentoVersion = $this->productMetadata->getVersion();
/** @var string $latestLtsNodeVersion */
$latestLtsNodeVersion = $this->escaper->escapeHtml($this->getLatestLtsNodeVersion());
$composerVersion = $this->getComposerVersion();
$npmVersion = $this->getNpmVersion();
$gitVersion = $this->getGitVersion();
$xdebugStatus = $this->getXdebugStatus();
$redisStatus = $this->getRedisStatus();
$searchEngineStatus = $this->getSearchEngineStatus();
$phpExtensions = $this->getImportantPhpExtensions();
$diskSpace = $this->getDiskSpace();
$nodeVersionDisplay = Comparator::lessThan($nodeVersion, $latestLtsNodeVersion)
? "<fg=yellow>$nodeVersion</> (Latest LTS: <fg=green>$latestLtsNodeVersion</>)"
: "$nodeVersion (Latest LTS: <fg=green>$latestLtsNodeVersion</>)";
$dbDisplay = $dbType . ' ' . $mysqlVersion;
$this->io->section('System Components');
$this->io->table(['Component', 'Version/Status'], [
['PHP', $phpVersion . ' (Memory limit: ' . $this->getPhpMemoryLimit() . ')'],
new TableSeparator(),
['Composer', $composerVersion],
new TableSeparator(),
['Node.js', $nodeVersionDisplay],
new TableSeparator(),
['NPM', $npmVersion],
new TableSeparator(),
['Git', $gitVersion],
new TableSeparator(),
['Database', $dbDisplay],
new TableSeparator(),
['Xdebug', $xdebugStatus],
new TableSeparator(),
['Redis', $redisStatus],
new TableSeparator(),
['Search Engine', $searchEngineStatus],
new TableSeparator(),
['OS', $osInfo],
new TableSeparator(),
['Disk Space', $diskSpace],
new TableSeparator(),
['Magento', $magentoVersion],
]);
if (!empty($phpExtensions)) {
$this->io->section('PHP Extensions');
$this->io->table(['Component', 'Version/Status'], $phpExtensions);
}
return Cli::RETURN_SUCCESS;
}
/**
* Get Node.js version
*
* @return string
*/
private function getNodeVersion(): string
{
try {
$output = trim($this->shell->execute('node -v 2>/dev/null'));
} catch (\Exception $e) {
return 'Not installed';
}
return $output !== '' ? ltrim($output, 'v') : 'Not installed';
}
/**
* Get latest LTS Node.js version
*
* @return string
*/
private function getLatestLtsNodeVersion(): string
{
try {
$httpClient = $this->httpClientFactory->create();
$httpClient->setTimeout(2);
$httpClient->get(self::NODE_LTS_URL);
if ($httpClient->getStatus() !== 200) {
return 'Unknown';
}
$nodeData = $httpClient->getBody();
if ($nodeData === '') {
return 'Unknown';
}
$nodes = json_decode($nodeData, true);
if (!is_array($nodes)) {
return 'Unknown';
}
/** @var array<int, array<string, mixed>> $nodes */
foreach ($nodes as $node) {
if (isset($node['lts'])
&& $node['lts'] !== false
&& isset($node['version'])
&& is_string($node['version'])
) {
return trim($node['version'], 'v');
}
}
return 'Unknown';
} catch (\Exception $e) {
if ($this->io->isVerbose()) {
$this->io->warning('Failed to fetch latest Node.js LTS version: ' . $e->getMessage());
}
return 'Unknown';
}
}
/**
* Get MySQL version
*
* @return string
*/
private function getShortMysqlVersion(): string
{
// Try different methods to get MySQL version
$version = $this->getMysqlVersionViaMagento();
if (!empty($version)) {
return $version;
}
$version = $this->getMysqlVersionViaClient();
if (!empty($version)) {
return $version;
}
return 'Unknown';
}
/**
* Get MySQL version via Magento connection
*
* @return string|null
*/
private function getMysqlVersionViaMagento(): ?string
{
try {
$connection = $this->resourceConnection->getConnection();
$select = $connection->select()->from(null, new \Zend_Db_Expr('VERSION()'));
$version = $connection->fetchOne($select);
return !empty($version) ? $version : null;
} catch (\Exception $e) {
if ($this->io->isVerbose()) {
$this->io->warning('Failed to read MySQL version via Magento connection: ' . $e->getMessage());
}
return null;
}
}
/**
* Get MySQL version via command line client
*
* @return string|null
*/
private function getMysqlVersionViaClient(): ?string
{
try {
$output = trim($this->shell->execute('mysql --version 2>/dev/null'));
} catch (\Exception $e) {
if ($this->io->isVerbose()) {
$this->io->warning('Failed to read MySQL version via client: ' . $e->getMessage());
}
return null;
}
if ($output !== '') {
preg_match('/Distrib ([0-9.]+)/', $output, $matches);
return isset($matches[1]) ? $matches[1] : null;
}
return null;
}
/**
* Get database type
*
* @return string
*/
private function getDatabaseType(): string
{
return 'MySQL'; // Only MySQL is supported in the current version
}
/**
* Get OS info
*
* @return string
*/
private function getShortOsInfo(): string
{
return php_uname('s') . ' ' . php_uname('r');
}
/**
* Get Composer version
*
* @return string
*/
private function getComposerVersion(): string
{
try {
$output = trim($this->shell->execute('composer --version 2>/dev/null'));
} catch (\Exception $e) {
return 'Not installed';
}
if ($output === '') {
return 'Not installed';
}
preg_match('/Composer version ([^ ]+)/', $output, $matches);
return isset($matches[1]) ? $matches[1] : 'Unknown';
}
/**
* Get NPM version
*
* @return string
*/
private function getNpmVersion(): string
{
try {
$output = trim($this->shell->execute('npm --version 2>/dev/null'));
} catch (\Exception $e) {
return 'Not installed';
}
return $output !== '' ? $output : 'Not installed';
}
/**
* Get Git version
*
* @return string
*/
private function getGitVersion(): string
{
try {
$output = trim($this->shell->execute('git --version 2>/dev/null'));
} catch (\Exception $e) {
return 'Not installed';
}
if ($output === '') {
return 'Not installed';
}
preg_match('/git version (.+)/', $output, $matches);
return isset($matches[1]) ? $matches[1] : 'Unknown';
}
/**
* Get Xdebug status
*
* @return string
*/
private function getXdebugStatus(): string
{
return extension_loaded('xdebug') ? 'Enabled' : 'Disabled';
}
/**
* Get Redis status
*
* @return string
*/
private function getRedisStatus(): string
{
return extension_loaded('redis') ? 'Enabled' : 'Disabled';
}
/**
* Get search engine status
*
* @return string
*/
private function getSearchEngineStatus(): string
{
// Method 1: Check Magento configuration
$magentoConfigResult = $this->getSearchEngineFromMagentoConfig();
if ($magentoConfigResult) {
return $magentoConfigResult;
}
// Method 2: Check PHP extensions
$extensionResult = $this->checkSearchEngineExtensions();
if ($extensionResult) {
return $extensionResult;
}
// Method 3: Check HTTP connection
$connectionResult = $this->checkSearchEngineConnections();
if ($connectionResult) {
return $connectionResult;
}
return 'Not Available';
}
/**
* Check search engine from Magento configuration
*
* @return string|null
*/
private function getSearchEngineFromMagentoConfig(): ?string
{
try {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
// First try via deployment config
$configResult = $this->checkSearchEngineViaDeploymentConfig($objectManager);
if ($configResult !== null) {
return $configResult;
}
// Then try via engine resolver
$resolverResult = $this->checkSearchEngineViaEngineResolver($objectManager);
if ($resolverResult !== null) {
return $resolverResult;
}
} catch (\Exception $e) {
if ($this->io->isVerbose()) {
$this->io->warning('Failed to read search engine config from Magento: ' . $e->getMessage());
}
}
return null;
}
/**
* Check search engine via Magento deployment config
*
* @param \Magento\Framework\ObjectManagerInterface $objectManager
* @return string|null
*/
private function checkSearchEngineViaDeploymentConfig($objectManager): ?string
{
try {
/** @var \Magento\Framework\App\DeploymentConfig $deploymentConfig */
$deploymentConfig = $objectManager->get(\Magento\Framework\App\DeploymentConfig::class);
$engineConfig = $deploymentConfig->get('system/search/engine');
if (!empty($engineConfig) && is_string($engineConfig)) {
$hostRaw = $deploymentConfig->get('system/search/engine_host');
$portRaw = $deploymentConfig->get('system/search/engine_port');
$host = is_string($hostRaw) ? $hostRaw : 'localhost';
$port = is_string($portRaw) ? $portRaw : '9200';
$url = "http://{$host}:{$port}";
if ($this->testElasticsearchConnection($url)) {
return ucfirst($engineConfig) . ' (Magento config)';
}
return ucfirst($engineConfig) . ' (Configured but not reachable)';
}
} catch (\Exception $e) {
if ($this->io->isVerbose()) {
$this->io->warning('Failed to read search engine from deployment config: ' . $e->getMessage());
}
}
return null;
}
/**
* Check search engine via Magento engine resolver
*
* @param \Magento\Framework\ObjectManagerInterface $objectManager
* @return string|null
*/
private function checkSearchEngineViaEngineResolver($objectManager): ?string
{
try {
/** @var \Magento\Framework\Search\EngineResolverInterface $engineResolver */
$engineResolver = $objectManager->get(\Magento\Framework\Search\EngineResolverInterface::class);
$currentEngine = $engineResolver->getCurrentSearchEngine();
if (!empty($currentEngine)) {
return ucfirst($currentEngine) . ' (Magento config)';
}
} catch (\Exception $e) {
if ($this->io->isVerbose()) {
$this->io->warning('Failed to read search engine via resolver: ' . $e->getMessage());
}
}
return null;
}
/**
* Check for search engine PHP extensions
*
* @return string|null
*/
private function checkSearchEngineExtensions(): ?string
{
if (extension_loaded('elasticsearch')) {
return 'Elasticsearch Available (PHP Extension)';
}
if (extension_loaded('opensearch')) {
return 'OpenSearch Available (PHP Extension)';
}
return null;
}
/**
* Check available search engine connections
*
* @return string|null
*/
private function checkSearchEngineConnections(): ?string
{
try {
$elasticHosts = $this->getSearchEngineHosts();
foreach ($elasticHosts as $url) {
$info = $this->testElasticsearchConnection($url);
if ($info !== false) {
return $this->formatSearchEngineVersion($info);
}
}
} catch (\Exception $e) {
if ($this->io->isVerbose()) {
$this->io->warning('Failed to check search engine connections: ' . $e->getMessage());
}
}
return null;
}
/**
* Get potential search engine hosts
*
* @return string[]
*/
private function getSearchEngineHosts(): array
{
$elasticHosts = [
'http://localhost:9200',
'http://127.0.0.1:9200',
'http://elasticsearch:9200',
'http://opensearch:9200',
];
$envHosts = [
'ELASTICSEARCH_HOST',
'ES_HOST',
'OPENSEARCH_HOST',
];
foreach ($envHosts as $envVar) {
$hostValue = $this->getEnvironmentVariable($envVar);
if (!empty($hostValue)) {
$port =
$this->getEnvironmentVariable('ELASTICSEARCH_PORT') ?? $this->getEnvironmentVariable(
'ES_PORT',
) ?? $this->getEnvironmentVariable('OPENSEARCH_PORT') ?? '9200';
$elasticHosts[] = "http://{$hostValue}:{$port}";
}
}
return $elasticHosts;
}
/**
* Format search engine version output
*
* @param array $info
* @phpstan-param array<string, mixed> $info
* @return string
*/
private function formatSearchEngineVersion(array $info): string
{
$version = $info['version'] ?? null;
if (!is_array($version)) {
return 'Search Engine Available';
}
if (isset($version['distribution']) && $version['distribution'] === 'opensearch') {
return 'OpenSearch ' . (is_string($version['number']) ? $version['number'] : '');
}
if (isset($version['number'])) {
return 'Elasticsearch ' . (is_string($version['number']) ? $version['number'] : '');
}
return 'Search Engine Available';
}
/**
* Test Elasticsearch connection and return version info
*
* @param string $url
* @return array<string, mixed>|false
*/
private function testElasticsearchConnection(string $url)
{
try {
// First attempt: Try using Magento's HTTP client
$magentoClientResult = $this->tryMagentoHttpClient($url);
if ($magentoClientResult !== null) {
return $magentoClientResult;
}
// No fallback to native approaches anymore - rely on Magento's HTTP client only
// This avoids using discouraged functions
} catch (\Exception $e) {
if ($this->io->isVerbose()) {
$this->io->warning('Search engine connection check failed: ' . $e->getMessage());
}
}
return false;
}
/**
* Try to connect using Magento's HTTP client
*
* @param string $url
* @return array<string, mixed>|null
*/
private function tryMagentoHttpClient(string $url): ?array
{
try {
$httpClient = $this->httpClientFactory->create();
$httpClient->setTimeout(2);
$httpClient->get($url);
$status = $httpClient->getStatus();
$response = $httpClient->getBody();
if ($status === 200 && !empty($response)) {
$data = json_decode($response, true);
if (is_array($data)) {
/** @var array<string, mixed> $data */
return $data;
}
}
} catch (\Exception $e) {
if ($this->io->isVerbose()) {
$this->io->warning('HTTP client request failed for search engine: ' . $e->getMessage());
}
}
return null;
}
/**
* Get important PHP extensions
*
* @return array<int, array<int, string>>
*/
private function getImportantPhpExtensions(): array
{
$extensions = [];
$requiredExtensions = [
'curl',
'dom',
'fileinfo',
'gd',
'intl',
'json',
'mbstring',
'openssl',
'pdo_mysql',
'simplexml',
'soap',
'xml',
'zip',
];
foreach ($requiredExtensions as $ext) {
$status = extension_loaded($ext) ? 'Enabled' : 'Disabled';
$extensions[] = [$ext, $status];
}
return $extensions;
}
/**
* Get PHP memory limit
*
* @return string
*/
private function getPhpMemoryLimit(): string
{
return ini_get('memory_limit');
}
/**
* Get disk space
*
* @return string
*/
private function getDiskSpace(): string
{
$totalSpace = disk_total_space('.');
$freeSpace = disk_free_space('.');
if ($totalSpace === false || $freeSpace === false) {
return 'Unknown';
}
if ($totalSpace <= 0) {
$totalGB = 0.0;
$usedGB = 0.0;
$usedPercent = 0.0;
return "$usedGB GB / $totalGB GB ($usedPercent%)";
}
$totalGB = round($totalSpace / 1024 / 1024 / 1024, 2);
$freeGB = round($freeSpace / 1024 / 1024 / 1024, 2);
$usedGB = round($totalGB - $freeGB, 2);
$usedPercent = $totalGB > 0.0
? round(($usedGB / $totalGB) * 100, 2)
: 0.0;
return "$usedGB GB / $totalGB GB ($usedPercent%)";
}
/**
* Safely get environment variable value
*
* @param string $name Environment variable name
* @param string|null $default Default value if not found
* @return string|null
*/
private function getEnvironmentVariable(string $name, ?string $default = null): ?string
{
// Try Magento-specific methods first
$magentoValue = $this->getMagentoEnvironmentValue($name);
if ($magentoValue !== null) {
return $magentoValue;
}
// Try system environment variables
$systemValue = $this->getSystemEnvironmentValue($name);
if ($systemValue !== null) {
return $systemValue;
}
return $default;
}
/**
* Get environment variable from Magento
*
* @param string $name Environment variable name
* @return string|null
*/
private function getMagentoEnvironmentValue(string $name): ?string
{
try {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
// Try via deployment config
$deploymentValue = $this->getValueFromDeploymentConfig($objectManager, $name);
if ($deploymentValue !== null) {
return $deploymentValue;
}
// Try via environment service
$serviceValue = $this->getValueFromEnvironmentService($objectManager, $name);
if ($serviceValue !== null) {
return $serviceValue;
}
} catch (\Exception $e) {
if ($this->io->isVerbose()) {
$this->io->warning('Failed to read Magento environment value: ' . $e->getMessage());
}
}
return null;
}
/**
* Get value from Magento deployment config
*
* @param \Magento\Framework\ObjectManagerInterface $objectManager
* @param string $name
* @return string|null
*/
private function getValueFromDeploymentConfig($objectManager, string $name): ?string
{
try {
/** @var \Magento\Framework\App\DeploymentConfig $deploymentConfig */
$deploymentConfig = $objectManager->get(\Magento\Framework\App\DeploymentConfig::class);
$envValue = $deploymentConfig->get('system/default/environment/' . $name);
if ($envValue !== null && is_scalar($envValue)) {
return (string) $envValue;
}
} catch (\Exception $e) {
if ($this->io->isVerbose()) {
$this->io->warning('Failed to read environment from deployment config: ' . $e->getMessage());
}
}
return null;
}
/**
* Get value from Magento environment service
*
* @param \Magento\Framework\ObjectManagerInterface $objectManager
* @param string $name
* @return string|null
*/
private function getValueFromEnvironmentService($objectManager, string $name): ?string
{
try {
$environmentService = $objectManager->get(\Magento\Framework\App\EnvironmentInterface::class);
$method = 'get' . str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower($name))));
if (is_object($environmentService) && method_exists($environmentService, $method)) {
$value = $environmentService->$method();
if ($value !== null) {
return (string) $value;
}
}
} catch (\Exception $e) {
if ($this->io->isVerbose()) {
$this->io->warning('Failed to read environment from service: ' . $e->getMessage());
}
}
return null;
}
/**
* Get environment variable from the system
*
* @param string $name Environment variable name
* @return string|null
*/
private function getSystemEnvironmentValue(string $name): ?string
{
// Use ini_get for certain system variables as a safer alternative
if (in_array($name, ['memory_limit', 'max_execution_time'])) {
$value = (string) ini_get($name);
if ($value !== '') {
return $value;
}
}
return null;
}
}